简单对比
UnityAction | UnityEvent | |
本质 | 委托 | 类 |
描述 | Unity中的一个零参数委托 | 是继承自UnityEventBase的类 |
用法 | 作为委托使用,常用于实现事件系统 | 通过addlistener可以注册一个事件,当这个UnityEvent被触发的时候,注册的事件就也会执行。 |
用法案例
public class Example : MonoBehaviour
{
UnityEvent m_MyEvent = new UnityEvent();
void Start()
{
//Add a listener to the new Event. Calls MyAction method when invoked
m_MyEvent.AddListener(MyAction);
}
void Update()
{
// Press Q to close the Listener
if (Input.GetKeyDown("q") && m_MyEvent != null)
{
Debug.Log("Quitting");
m_MyEvent.RemoveListener(MyAction);
#if UNITY_EDITOR
UnityEditor.EditorApplication.isPlaying = false;
#endif
}
//Press any other key to begin the action if the Event exists
if (Input.anyKeyDown && m_MyEvent != null)
{
//Begin the action
m_MyEvent.Invoke();
}
}
void MyAction()
{
//Output message to the console
Debug.Log("Do Stuff");
}
}
按下空格键之后的输出样式: