NetWorkManager:
Player:
PlayerCT Cood:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
//[System.Obsolete]
public class PlayerCT : NetworkBehaviour
{
public int rotateSpeed = 120;
public int moveSpeed = 3;
public GameObject Bullet;
public Transform firePoint;
// Update is called once per frame
void Update()
{
if (isLocalPlayer == false)//控制本地角色
return;
float h = Input.GetAxis("Horizontal");
float v = Input.GetAxis("Vertical");
transform.Rotate(Vector3.up * h * rotateSpeed * Time.deltaTime);
transform.Translate(Vector3.forward * v * moveSpeed * Time.deltaTime);
if (Input.GetKeyDown(KeyCode.Space))
{
CmdFire();
}
}
[Command]//客户端发起调用,服务端执行
void CmdFire()//服务端调用的方法以Cmd开头
{
GameObject bullet = Instantiate(Bullet, firePoint.position, firePoint.rotation);
bullet.GetComponent<Rigidbody>().velocity = transform.forward * 10;//Bulet预制体添加Network Transform监测刚体组件(初始监测一次施加速度)
Destroy(bullet, 2f);//2s后销毁
NetworkServer.Spawn(bullet);//服务端执行同步到客户端
}
public override void OnStartLocalPlayer()//回调函数:加角色时执行
{
GetComponent<MeshRenderer>().material.color = Color.blue;
//firePoint = transform.Find("FirePoint").GetComponent<Transform>();
}
}
Player Health Cood:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Networking;
[System.Obsolete]
public class Health : NetworkBehaviour
{
private Slider hpSl;
public const int hp = 100;
[SyncVar(hook ="OnChangeHealth")]//特性:变量数据同步到客户端,变量变化时调用方法“方法名”
private int currentHp = hp;
private void Start()
{
hpSl = transform.Find("Canvas/HpSlider").GetComponent
}
public void TakeDamage(int damege)
{
if (isServer == false)//服务端执行,同步到客户端
return;
currentHp -= damege;
if (currentHp <=0)
{
currentHp = hp;
Debug.Log("Dead");
//Destroy(this.gameObject);
RpcRespown();//角色复位
}
}
void OnChangeHealth(int health)//[SyncVar hook="方法"]特性标记的变量值发生变化时执行
{
hpSl.value = health / (float)hp;
}
[ClientRpc]//客户端调用
void RpcRespown()//客户端调用以Rpc开头
{
if (isLocalPlayer == false)//本地角色执行
return;
transform.position = Vector3.zero;
}
}
Bullet Cood:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Bullet : MonoBehaviour
{
[System.Obsolete]
private void OnCollisionEnter(Collision collision)
{
GameObject hit = collision.gameObject;
Health health = hit.GetComponent
if (health !=null)
{
health.TakeDamage(Random.Range(10, 21));
Destroy(this.gameObject);
}
}
}