Unity UNET - 在播放器对象外调用 [Command]

Unity UNET - calling [Command] outside of player object

所以我明白 [command] 对非玩家对象不起作用,但是...为什么?我应该如何同步非玩家对象的数据,例如 NPC 位置。在非玩家对象上调用 Command 的能力将在每个客户端上节省大量重复计算时间。

有没有人想出解决这个设计决定的方法?

此外,似乎 SyncVars 如果不在播放器对象上也不会同步。

现在我最好的策略是在玩家对象上存储大量数据,并且必须不断从外部引用它 类

编辑: 糟糕,我的错误,正如指出的那样,SyncVars 正在处理非玩家对象,只是在服务器上更新时才如此

是的,[命令] 用于将玩家 RPC 发送到服务器。

但是,SyncVars 将在任何具有 NetworkBehaviour 的对象(不仅仅是玩家对象)上将状态从服务器同步到客户端。

权威服务器方法是让服务器使用 NetworkServer.Spawn() 生成您的 NPC 位置,然后更新 NPC Syncvars,它们会自动在所有客户端上更新。

如果您确实需要从客户端发送 [命令],使用新版本的 Unity,您可以使用 AssignClientAuthority() 授予场景对象本地玩家权限:

如果您拥有 PRO 许可证并且可以访问 Unity 5.2 beta 版本,那么他们将其添加到 5.2b1

Networking: Added support for client-side authority for non-player objects. The new function NetworkServer.SpawnWithClientAuthority(GameObject obj, NetworkConnection conn) allows authority to be assigned to a client by its connection when an object is created. This would typically be used in a command handler for a client asking to spawn an object, then the client's connection would be passed in. For example:

[Command] 
void CmdSpawn() { 
    var go = (GameObject)Instantiate(otherPrefab,
    transform.position + new Vector3(0,1,0), Quaternion.identity);
    NetworkServer.SpawnWithClientAuthority(go, base.connectionToClient); 
}

For setting the authority on objects after they are created, there are the new functions AssignClientAuthority(NetworkConnection conn) and RemoveClientAuthority(NetworkConnection conn) on the NetworkIdentity class. Note that only one client can be the authority for an object at a time. On the client that has authority, the function OnStartAuthority() is called, and the property hasAuthority will be true. The set of objects that is owned by a client is available in the new property NetworkConnection.clientOwnedObjects which is a set of NetworkInstanceIds. This set can be used on the server when a message is received to ensure that the client that sent the message actually owns the object. When a client disconnects, the function DestroyPlayersForConnection now destroys all the objects owned by that connection, not just the player object. Objects which have their authority set to a client must have LocalPlayerAuthority set in their NetworkIdentity. Previously only player objects could have local authority, which meant that the NetworkTransform (and other components) could only be used for controlling the single player object for a connection on a client. With these changes it is possible to have multiple objects on a client that are locally controlled.