文档

Unity 引擎

Unity 引擎

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 窗口中配置它们。
UnityEvent
可以添加到 Any
MonoBehaviour
中,并在运行时像标准 C# 委托一样执行。在
MonoBehaviour
中声明
UnityEvent
时,该函数将显示在
Inspector員

?

窗口中,您可以在其中定义在编辑时间和运行时之间持续存在的回调。
Unity 事件具有与标准 C# 委托类似的限制:
  • 它们保存对 Target Object 的引用,从而停止对 Target Object 进行垃圾收集。
  • 如果目标为 Managed (C#)
    UnityEngine.Object
    ,而非 Managed (C++) 对应对象已被销毁,则不会调用回调。有关更多信息,请参阅对象。

Configure Unity 事件

先决条件

  • 创建包含
    using UnityEngine.Events
    的 MonoBehaviour 脚本
  • 声明至少一个
    UnityEvent
    类型的 Field

在 Inspector 窗口中Configure回调:

  1. 选择包含包含您声明的
    UnityEvent
    Field 的脚本组件的游戏对象。
  2. 单击事件Name下的 + 按钮可添加回调字段。
  3. 选择要接收回调的 UnityEngine.Object。您可以使用对象选择器器或将Object拖放到Field中。
  4. 选择要在事件发生When调用的函数。Dropdown 选择器中填充了游戏对象及其组件可用的相应方法的过滤列表。
  5. 根据需要重复步骤 1-4 为同一事件添加其他回调。

Configuring callbacks for events called Trigger Entered and Trigger Exited in the Inspector window

Static和动态Calls

在 Inspector 窗口中配置
UnityEvent
时,支持两种类型的函数 Calls:
  • Static Calls 在创作时间完全预先配置,其 Target 和参数值在 Inspector 窗口中定义。调用回调When,将使用 Inspector 中定义的参数值调用Target函数。此属性适用于在运行时不会改变的值,例如,当您希望每次发生特定碰撞时将 Health 值减少设置的 amount 时。静态绑定的函数显示在函数选择列表中的 Static 参数下。
  • 动态 Calls 是从代码中以编程方式调用的,参数与调用的
    UnityEvent
    类型匹配。这适用于在运行时变化的值,例如一个
    float
    表示角色每次攻击 ON 受到的可变伤害金额。UI 过滤回调,仅显示具有对
    UnityEvent
    类型有效的签名的动态函数。例如,如果有
    UnityEvent<string>
    ,函数选择器会在动态字符串标头下列出接受
    string
    参数的任何函数。

Choosing between static or dynamic functions whose signatures match the event type in the Inspector window

UnityEvent 中的 Generic Support

默认情况下,
Monobehaviour
中的
UnityEvent
动态绑定到
void
函数。但您可以创建最多包含四个 Generic 类型 Parameters 的
UnityEvent
,如下例所示:
using 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); } }}

其他资源