Unity 内置 同步变量 支持同步一些数据类型
同步变量可以是基础类型,如整数,字符串和浮点数。也可以是Unity内置数据类型,如Vector3和用户自定义的结构体,但是对结构体类型的同步变量,如果只有几个字段的数值有变化,整个结构体都会被发送。每个NetworkBehaviour脚本可以有最多32个同步变量
但是要是 同步 GameObject 列表呢?
其实很巧妙
有个前提只能同步 LocalPlayer
public List<GameObject> localCopyOfList = new List<GameObject>();
public void AddToList(GameObject obj)
{
if (!isLocalPlayer)
throw new InvalidOperationException("This can only be called for the local player!");
if (obj.GetComponent<NetworkIdentity>() == null)
throw new InvalidOperationException("Network only knows about GameObjects that have a NetworkIdentity!");
CmdAddToList(obj);
}
[Command]
void CmdAddToList(GameObject obj)
{
// this code is only executed on the server
RpcAddToList(obj); // invoke Rpc on all clients
}
[ClientRpc]
void RpcAddToList(GameObject obj)
{
// this code is executed on all clients
localCopyOfList.Add(obj);
}