我需要修改一个非玩家对象。我能够做到,但由于某些原因,我收到警告:
Trying to send command for object without authority.
UnityEngine.Networking.NetworkBehaviour:SendCommandInternal(NetworkWriter, Int32, String)
ModelControl:CallCmdSetCube()
ModelControl:Update() (at Assets/Scripts/ModelControl.cs:21)
我已经阅读了统一文档和各种答案,但奇怪的是它确实有效,但我希望阻止警告。
首先有一个创建中性对象的 Manager 对象。这发生在主机上。
public class ObjectControl : NetworkBehaviour
{
public GameObject cube;
public override void OnStartServer()
{
if (GameObject.Find("Cube") != null) { return; }
GameObject cubeInstance = (GameObject)Instantiate(this.cube,
new Vector3(0f, 0f, 5f), Quaternion.identity);
cubeInstance.name = "Cube";
NetworkServer.Spawn(cubeInstance);
}
}
然后每个玩家都有以下内容:
private void CmdSetCube()
{
GameObject cube = GameObject.Find("Cube"); // This is the neutral object
if (cube != null)
{
NetworkIdentity ni =cube.GetComponent<NetworkIdentity>();
ni.AssignClientAuthority(connectionToClient);
RpcPaint(cube, new Color(Random.Range(0f, 1f), Random.Range(0f, 1f), Random.Range(0f, 1f)));
ni.RemoveClientAuthority(connectionToClient);
}
}
[ClientRpc]
void RpcPaint(GameObject obj, Color col)
{
obj.GetComponent<Renderer>().material.color = col;
}
主机不会触发警告。只有远程客户端会收到警告。当我有很多客户端时,我可以在编辑器控制台中看到它会打印多少次客户端。但同样,它确实有效,我可以看到新数据正在传播到所有会话,但我预计稍后会出现一些问题。