解决问题
可以用于Unity的事件处理,但是使用时要保证参数个数、类型、顺序必须完全⼀致。
代码
委托事件中心
_Delegation.cs
using System;
public class _Delegation
{
/// <summary>
/// 一个参数
/// </summary>
public static Action<string> onShowText;
public static void OnShowText(string str)
{
if (onShowText == null) return;
onShowText(str);
}
/// <summary>
/// 二个参数
/// </summary>
public static Action<string, int> onDenugText;
public static void OnDenugText(string str,int n)
{
if (onDenugText == null) return;
onDenugText(str, n);
}
}
测试脚本,添加委托处理的方法
ShowText.cs
using UnityEngine;
using UnityEngine.UI;
public class ShowText : MonoBehaviour
{
private Text showText;
private void Awake()
{
showText = transform.Find("ShowText").GetComponent<Text>();
}
private void OnEnable()
{
_Delegation.onShowText += OnShowText;
_Delegation.onDenugText += OnDebugText;
}
private void OnDisable()
{
_Delegation.onShowText -= OnShowText;
_Delegation.onDenugText -= OnDebugText;
}
public void OnShowText(string str)
{
showText.text = "字符串:" + str;
}
public void OnDebugText(string str, int n)
{
showText.text = "字符串:"+str+",数字:"+n;
}
}
测试脚本,显示委托处理的效果
DelegationTest.cs
using UnityEngine;
using UnityEngine.UI;
public class DelegationTest : MonoBehaviour
{
public Button testBt1;
public Button testBt2;
void Start()
{
testBt1.onClick.AddListener(() =>
{
_Delegation.OnShowText("OnShowText");
});
testBt2.onClick.AddListener(() =>
{
_Delegation.OnDenugText("OnDebugText", 2021);
});
}
}
脚本挂载及运行效果
如图,UI中有两个Button组件(TestBt1、TestBt2)和一个Text(ShowText)组件,还有一个空物体(DelegationTest),将DelegationTest .cs挂在空物体上,将ShowText挂在Canvas上,然后将UI组件添加上去,然后运行。分别点击不同的按钮,会输出不同的字符。