跳到主要内容

Command Event

在 Command 中我们不能使用 UnityEvent,因为 UnityEvent 不支持跨场景引用。因此,我们使用 CommandEvent 来实现相同的功能。

CommandEvent 不仅仅是替代品,它还提供了一些 UnityEvent 不具备的能力。一个 command event 支持 public 的 setter 属性,以及最多带四个参数的方法,支持的参数类型如下:

  • string
  • float
  • int
  • bool
  • Color
  • AnimationCurve
  • Vector3
  • Vector3Int
  • Vector2
  • Vector2Int
  • Vector4
  • Rect
  • Bounds
  • Enum
  • UnityEngine.Object及其子类
  • TargetObject<>

UnityEvent 一样,command event 同时支持静态参数和动态参数。

静态参数

当声明为不带泛型参数的 CommandEvent 时,事件会使用在 Command Node 中定义的静态参数来调用回调。

...
public class InvokeEventExampleCommand : Command, ICommandAutoDraw
{

public override float nodeWidth => 350f;

public CommandEvent myEvent;

public override void Execute(CommandExecutionFlow _flow)
{
myEvent?.Invoke();
Exit();
}
}

如果你只需要一个简单的 Command 来触发 CommandEvent,那么内置的 Invoke Event Command 已经可以满足需求。不过,如果在调用事件之前还需要更复杂的条件判断,那么就需要创建自定义 Command。

动态参数

当参数无法在 Command Node 中预先定义,而只能在运行时获取时,就需要使用带动态参数的 CommandEvent

UnityEvent 类似,我们同样可以通过声明一个继承自 CommandEvent<> 的类,来创建属于自己的动态 command event 类型。

[System.Serializable]
[RegisterCommand("Custom/Invoke Int Event", typeof(SequineFlowCommandData))]
public class InvokeIntEventCommand : Command, ICommandAutoDraw
{
public override float nodeWidth => 350f;

[System.Serializable]
public class IntEvent : CommandEvent<int> { }

public IntEvent myIntEvent;

public override void Execute(CommandExecutionFlow _flow)
{
int randomInt = Random.Range(0, 100);
myIntEvent?.Invoke(randomInt);
Exit();
}

}