UnityAction 和UnityEvent的用法
  EFTJ6596AiAP 2023年11月02日 103 0

简单对比


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");
}
}

按下空格键之后的输出样式:

UnityAction 和UnityEvent的用法_事件系统

【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年11月08日 0

暂无评论

EFTJ6596AiAP