Inspector 可配置的 Custom Events
创建自己的 Custom Events 以在 Inspector 窗口中配置持久性(lasting between Edit mode and Play mode)回调。
阅读时间4 分钟最后更新于 6 天前
Unity 提供了 UnityEvent API 作为 Unity 指定的替代标准 C# 事件和委托。Unity 事件比标准 C# 事件的主要优点是 Unity 事件可 Serializable,这意味着可以在 Inspector 窗口中配置它们。
UnityEventMonoBehaviourMonoBehaviourUnityEventInspector員
?
Unity 事件具有与标准 C# 委托类似的限制:
- 它们保存对 Target Object 的引用,从而停止对 Target Object 进行垃圾收集。
- 如果目标为 Managed (C#) ,而非 Managed (C++) 对应对象已被销毁,则不会调用回调。有关更多信息,请参阅对象。
UnityEngine.Object
Configure Unity 事件
先决条件
- 创建包含 的 MonoBehaviour 脚本
using UnityEngine.Events - 声明至少一个 类型的 Field
UnityEvent
在 Inspector 窗口中Configure回调:
-
选择包含包含您声明的Field 的脚本组件的游戏对象。
UnityEvent -
单击事件Name下的 + 按钮可添加回调字段。
-
选择要接收回调的 UnityEngine.Object。您可以使用对象选择器器或将Object拖放到Field中。
-
选择要在事件发生When调用的函数。Dropdown 选择器中填充了游戏对象及其组件可用的相应方法的过滤列表。
-
根据需要重复步骤 1-4 为同一事件添加其他回调。
Configuring callbacks for events called Trigger Entered and Trigger Exited in the Inspector window
Static和动态Calls
在 Inspector 窗口中配置时,支持两种类型的函数 Calls:
UnityEvent- Static Calls 在创作时间完全预先配置,其 Target 和参数值在 Inspector 窗口中定义。调用回调When,将使用 Inspector 中定义的参数值调用Target函数。此属性适用于在运行时不会改变的值,例如,当您希望每次发生特定碰撞时将 Health 值减少设置的 amount 时。静态绑定的函数显示在函数选择列表中的 Static 参数下。
- 动态 Calls 是从代码中以编程方式调用的,参数与调用的类型匹配。这适用于在运行时变化的值,例如一个
UnityEvent表示角色每次攻击 ON 受到的可变伤害金额。UI 过滤回调,仅显示具有对float类型有效的签名的动态函数。例如,如果有UnityEvent,函数选择器会在动态字符串标头下列出接受UnityEvent<string>参数的任何函数。string
Choosing between static or dynamic functions whose signatures match the event type in the Inspector window
UnityEvent 中的 Generic Support
默认情况下,中的动态绑定到 函数。但您可以创建最多包含四个 Generic 类型 Parameters 的,如下例所示:
MonobehaviourUnityEventvoidUnityEventusing UnityEngine;using UnityEngine.Events;public class GenericTest :MonoBehaviour{ public UnityEvent<int, int, bool, string> myEvent; // Start is called once before the first execution of Update after the MonoBehaviour is created void Start() { if (myEvent == null) { myEvent = new UnityEvent<int, int, bool, string>(); } myEvent.AddListener(Ping); } // Update is called once per frame void Update() { if (Input.anyKeyDown && myEvent != null) { myEvent.Invoke(5, 6, true, "Hello"); } } void Ping(int i, int j, bool print, string text) { if (print) { Debug.Log("Ping: " + text + i + j); } }}