说明:
[Commands]命令是由客户端(或具有客户端权限的其他GameObject)发送到服务端,并在服务端运行;
[ClientRpc]命令是由服务端发送到连接到服务端的每一个客户端并在客户端运行;
[SyncVar]将服务端的变量同步到客户端。
1.创建一个Sphere,命名为Bullet,比例为(0.2,0.2,0.2),添加NetworkIdentity、NetworkTransform、Rigibody(去掉Use gravity)。拖入Assets,生成预制件Bullet.prefab。删除场景中的Bullet实体。
2.修改PlayerController.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
//注意继承至NetworkBehaviour
public class PlayerController : NetworkBehaviour {
//1.新增:子弹prefab
public GameObject bulletPrefab;
//2.新增:子弹初始位置
public Transform bulletSpawn;
void Update()
{
//只操作代表自己的那个Player,如果没有这个判断,其他的Player也会跟着动
if (!isLocalPlayer)
return;
var x = Input.GetAxis("Horizontal") * Time.deltaTime * 150.0f;
var z = Input.GetAxis("Vertical") * Time.deltaTime * 3.0f;
transform.Rotate(0, x, 0);
transform.Translate(0, 0, z);
//3.新增:按空格发布子弹
if (Input.GetKeyDown(KeyCode.Space))
{
CmdFire();
}
}
//
public override void OnStartLocalPlayer()
{
//代表自己的那个Player为蓝色,其他的Player颜色默认
GetComponent().material.color = Color.blue;
}
//4.新增:Command的意思是在服务端执行
[Command]
void CmdFire()
{
GameObject bullet = (GameObject)Instantiate(bulletPrefab, bulletSpawn.position, bulletSpawn.rotation);
bullet.GetComponent().velocity = bullet.transform.forward * 6.0f;
//在服务端上生成有速度的子弹
NetworkServer.Spawn(bullet);
//子弹两秒后销毁
Destroy(bullet, 2);
}
}
3.将Player.prefab拖入场景,在Player下创建一个Cylinder和一个空物体SpawnPos,Cylinder用户表示枪管(需要自己调整),SpawnPos用来表示子弹的初始位置,放在枪口。设置PlayerController中的bulletPrefab和bulletSpawn。点击Inspector上【Apply】按钮,使预制件的修改生效。删除场景中的player。
4.将Bullet.prefab拖入NetworkManager的NetworkManager组件【Spawn Info】【Registered Spawnable Prefabs】列表中。
5.发布测试,客户端的子弹可以同步了。