Command(命令)属性
1,修饰方法的,当在客户端调用此方法,它将在服务端运行(我的理解:客户端命令服务端做某事;或者说:客户端向服务端发消息,消息=方法)
2,默认只能从玩家对象发送命令
requiresAuthority=false绕过权限检查,这样就可以从任意网络对象上发送命令
示例:客户端点击按钮,服务端图片变红
从玩家对象发送命令
using Mirror;
using UnityEngine;
using UnityEngine.UI;
public class CommandTest : NetworkBehaviour
{
public Image image;
public Toggle toggle;
void Start()
{
image = GameObject.Find("Image").GetComponent<Image>();
toggle = GameObject.Find("Toggle").GetComponent<Toggle>();
if (isServer)
{
toggle.gameObject.SetActive(false);
image.gameObject.SetActive(true);
}
else
{
toggle.gameObject.SetActive(true);
image.gameObject.SetActive(false);
}
toggle.onValueChanged.AddListener((isOn) =>
{
ChangeColor(isOn);
});
}
[Command]
void ChangeColor(bool isOn)
{
if (isOn)
image.color = Color.red;
else
image.color = Color.white;
}
}
从任意一网络对象发送命令
using Mirror;
using UnityEngine;
using UnityEngine.UI;
public class CommandTest : NetworkBehaviour
{
public Image image;
public Toggle toggle;
void Start()
{
if (isServer)
{
toggle.gameObject.SetActive(false);
image.gameObject.SetActive(true);
}
else
{
toggle.gameObject.SetActive(true);
image.gameObject.SetActive(false);
}
toggle.onValueChanged.AddListener((isOn) =>
{
ChangeColor(isOn);
});
}
[Command(requiresAuthority = false)]
void ChangeColor(bool isOn)
{
if (isOn)
image.color = Color.red;
else
image.color = Color.white;
}
}