2

我想创建一个简单的演示。我希望在平面中间有一个立方体,当您单击它时会改变颜色。(这很容易实现)我希望有两个玩家轮流点击立方体。只有轮到你时,立方体才会改变颜色。如果立方体改变颜色,改变将反映在两个玩家的屏幕上。我一直在查看 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

4

1 回答 1

2

多亏了这篇StackOverflow 帖子,我终于能够让它工作了。

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

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

}
于 2015-12-12T06:14:28.377 回答