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

时间:2015-12-09 23:46:59

标签: c# unity3d unity5 unity-networking

我想创建一个简单的演示。我希望在平面中间有一个立方体,当你点击它时会改变颜色。 (这很容易实现) 我希望有两个玩家,轮流点击立方体。 如果轮到您,立方体只会改变颜色。如果立方体改变颜色,则更改将反映在玩家的屏幕上。 我一直在看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目前不是预制件。我启用了网络标识组件,以及网络转换 - &gt;同步转换。当我启动服务器主机时,我可以更改块的颜色,但客户端无法查看这些更改。当客户端单击该块时,没有任何反应,除了错误消息:尝试在没有权限的情况下向对象发送命令。

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

1 个答案:

答案 0 :(得分:2)

所以我终于能够让这个工作了,感谢这个StackOverflow post

这是我的脚本,我将它附加到播放器对象,而不是我希望通过网络同步的非游戏对象。

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;
    }

}