Unity Mirror学习(二) Command特性使用

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

快乐教主

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值