Unity委托实例应用

委托:顾名思义就是把一件或多件事情委托给别的人去做 

在程序里面就是把定义的事件或者方法指向一个委托方法 当调用委托的时候全部执行

下面我们用实际应用

三个人排队取餐 喊到谁 谁答应一下  

先定义一个委托的管理器 一个button事件来执行

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;


//定义一个委托
public delegate void VoidDelegate(string s);
public class PlayerCtr : MonoBehaviour
{

    public static VoidDelegate callOutDelegate;

    public Button resultBtn;
    public Text showTxt;
    public InputField inputTxt;
    // Start is called before the first frame update
    void Start()
    {
        resultBtn.onClick.AddListener(ResultClick);
    }


    private void ResultClick()
    {
        showTxt.text = "这是谁的东西";
        callOutDelegate?.Invoke(inputTxt.text);
    }

}

然后定义三个玩家 (用一个class来是实现)

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class Player : MonoBehaviour
{
    // Start is called before the first frame update
    public string foodName;//对应商品的名字
    void Start()
    {
        PlayerCtr.callOutDelegate += Listen;
    }



    private void Listen(string s)
    {
        if (s.Equals(foodName))
        {
            transform.GetComponent<Text>().text = $"这是我的{foodName}";
        }
        else
        {
            transform.GetComponent<Text>().text = $"这不是我的";

        }
    }

    private void OnDestroy()
    {
        PlayerCtr.callOutDelegate -= Listen;
    }
}

unity 挂载如下

player脚本挂在之后输入对应的商品名字 以便后面喊话收到通知

为了方便我直接用的拖拽 

完成之后然后运行程序 在输入框输入对应的商品 点击确定 会把事件同时分发给三个player 并给出反馈

有兴趣的可以尝试一下!!!

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值