UNET 多人游戏,让两个玩家都与 gameObject 交互,更改在主机和客户端上同步

UNET Multi-Player game, having both players interact with gameObject, changes synchronized on host and client

我想创建一个简单的演示。我希望在平面中间有一个立方体,当您单击它时它会改变颜色。 (这很容易实现) 我希望有两名玩家轮流点击立方体。 只有轮到你时,立方体才会改变颜色。如果立方体改变颜色,这种变化将反映在双方玩家的屏幕上。 我一直在查看 UNET http://forum.unity3d.com/threads/unet-sample-projects.331978/ 的示例,其中大多数都有一个您可以用键盘控制的网络角色,这方面让我失望。我是否还需要创建 2 个玩家,但只是让他们不可见并且没有控制脚本?我的积木应该是预制件吗?这是我的块脚本:

void Update()
{
      if (Input.GetKeyDown(KeyCode.Space))  
      {
          // Command function is called from the client, but invoked on the server
           CmdChangeColor();
       }
 }

[Command]
void CmdChangeColor()
{
      if (cubeColor == Color.green) cubeColor = Color.magenta;
      else if (cubeColor == Color.magenta) cubeColor = Color.blue;
      else if (cubeColor == Color.blue) cubeColor = Color.yellow;
      else if (cubeColor == Color.yellow) cubeColor = Color.red;
      else cubeColor = Color.green;

      GetComponent<Renderer>().material.color = cubeColor;
 }

另外我会注意到我的 Block 目前不是预制件。我启用了网络身份组件,以及网络转换->同步转换。当我启动服务器主机时,我可以更改块的颜色,但客户端无法查看这些更改。当客户端单击该块时,没有任何反应,除了错误消息:Trying to send command to the object without authority.

如有任何帮助,我们将不胜感激!谢谢 http://docs.unity3d.com/Manual/UNetSetup.html

多亏了这个

所以我终于能够让它工作了

这是我的脚本,我将它附加到玩家对象,而不是我想通过网络同步的非游戏对象。

using UnityEngine;
using System.Collections;
using UnityEngine.Networking;

public class OnTouchEvent : NetworkBehaviour
{
    //this will get called when you click on the gameObject
    [SyncVar]
    public Color cubeColor;
    [SyncVar]
    private GameObject objectID;
    private NetworkIdentity objNetId;


    void Update()
    {
        if (isLocalPlayer)
        {
            CheckIfClicked();
        }
    }

    void CheckIfClicked()
    {
        if (isLocalPlayer && Input.GetMouseButtonDown(0))
        {
            objectID = GameObject.FindGameObjectsWithTag("Tower")[0];                         //get the tower                                   
            cubeColor = new Color(Random.value, Random.value, Random.value, Random.value);    // I select the color here before doing anything else
            CmdChangeColor(objectID, cubeColor);
        }
    }



    [Command]
    void CmdChangeColor(GameObject go, Color c)
    {
        objNetId = go.GetComponent<NetworkIdentity>();        // get the object's network ID
        objNetId.AssignClientAuthority(connectionToClient);    // assign authority to the player who is changing the color
        RpcUpdateCube(go, c);
        // use a Client RPC function to "paint" the object on all clients
        objNetId.RemoveClientAuthority(connectionToClient);    // remove the authority from the player who changed the color
    }

    [ClientRpc]
    void RpcUpdateCube(GameObject go, Color c)
    {
        go.GetComponent<Renderer>().material.color = c;
    }

}