我想创建一个简单的演示。我希望在平面中间有一个立方体,当您单击它时它会改变颜色。 (这很容易实现) 我希望有两个玩家,轮流点击立方体。 只有轮到你时,立方体才会改变颜色。如果立方体改变颜色,这种变化将反射(reflect)在两个玩家的屏幕上。 我一直在查看 UNET 的示例,http://forum.unity3d.com/threads/unet-sample-projects.331978/ ,而且大多数都有一个网络角色,你可以用键盘控制这个角色,这方面让我很失望。我是否仍然需要创建 2 个玩家,但只是让他们不可见并且没有控制脚本?我的 block 应该是预制件吗?这是我的 block 的脚本:
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 当前不是预制件。我启用了网络身份组件,以及网络转换->同步转换。当我启动服务器主机时,我可以更改 block 的颜色,但客户端无法查看这些更改。当客户端单击该 block 时,除了错误消息之外,没有任何反应:尝试在未经授权的情况下向对象发送命令。
如有任何帮助,我们将不胜感激!谢谢 http://docs.unity3d.com/Manual/UNetSetup.html
最佳答案
多亏了这个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;
}
}
关于c# - UNET 多人游戏,让两个玩家与游戏对象交互,在主机和客户端上同步更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34191207/