委托:顾名思义就是把一件或多件事情委托给别的人去做
在程序里面就是把定义的事件或者方法指向一个委托方法 当调用委托的时候全部执行
下面我们用实际应用
三个人排队取餐 喊到谁 谁答应一下
先定义一个委托的管理器 一个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 并给出反馈