<span style="font-size:14px;">using UnityEngine;
using System.Collections;
//Unity声明委托事件
public class Test : MonoBehaviour {
public delegate void TestHandler(int number); //声明代理
public static event TestHandler TestEvent;//声明事件
void Update()
{
//按下键盘A键
if (Input.GetKeyDown(KeyCode.A))
{
if (TestEvent != null)
{
TestEvent(10);
}
}
}
}</span>
在其他脚本中添加委托事件
<span style="font-size:14px;">void OnEnable()
{
//开始调用脚本时添加委托事件
Test.TestEvent += GetEvent;
}
void OnDisable()
{
//当对象销毁时去掉委托事件
Test.TestEvent -= GetEvent;
}
private void GetEvent(int num)
{
Debug.Log(num);
}</span>
这样做的好处是,不用获取到其他脚本,即可调用其他脚本中的对象,或者向其他对象传递信息