概述 OVERVIEW
GameplayMessageRouter 是 Lyra 示例项目中的插件,提供一种不绑定特定对象的“消息总线”:发送方与接收方只通过 GameplayTag 频道通信,彼此无需持有引用。
消息总线本身在游戏开发中很常见,用纯蓝图也能连出一套类似的东西。我认为这个插件真正的价值,在于它对蓝图节点的定制所带来的易用性。读完源码,可以学到以下四件事:
| # | 学习要点 OBJECTIVES | SEE |
|---|---|---|
| 01 | 引擎插件与 Subsystem 的正确用法 | §2 → |
| 02 | 在 C++ 中自定义异步节点 | §3 → |
| 03 | 细化到蓝图节点针脚的定制 | §4 → |
| 04 | 蓝图与 C++ 的不定类型结构体交互 | §2.3 → |
核心实现 SUBSYSTEM
插件的核心方法都在 UGameplayMessageSubsystem 中。它继承自 UGameInstanceSubsystem,生命周期与 GameInstance 一致、全局唯一,无需手动创建。整体结构见 FIG. 2-1。
- BLUEPRINT · 蓝图Listen For Gameplay Messages用户看到的节点
- EDITOR · GameplayMessageNodesUK2Node_AsyncAction_ListenForGameplayMessages编译时展开针脚
- RUNTIMEUAsyncAction_ListenForGameplayMessage注册 / 注销 Listener
- SUBSYSTEMUGameplayMessageSubsystemListenerMap:Tag → Listeners
BroadcastMessage(Channel, Message) ──▶ Subsystem ──▶ 匹配的 Listener 回调
UCLASS()
class GAMEPLAYMESSAGERUNTIME_API UGameplayMessageSubsystem : public UGameInstanceSubsystem
{
GENERATED_BODY()
protected:
// 向指定 GameplayTag 广播消息
UFUNCTION(BlueprintCallable, CustomThunk, meta=(CustomStructureParam="Message"))
void K2_BroadcastMessage(FGameplayTag Channel, const int32& Message);
DECLARE_FUNCTION(execK2_BroadcastMessage);
private:
void BroadcastMessageInternal(FGameplayTag Channel, const UScriptStruct* StructType, const void* MessageBytes);
// 保存 Tag 和 Listener 关系的 Map
TMap<FGameplayTag, FChannelListenerList> ListenerMap;
};- 1LINE 07CustomThunk:UHT 不再生成默认 exec 函数;CustomStructureParam 把 Message 变成通配针脚。
- 2LINE 08int32 只是占位类型,真正的结构体类型在运行时从栈上取得。
- 3LINE 13Tag → 监听者列表。PartialMatch 时会沿父级 Tag 逐层向上匹配。
ListenerMap 以 GameplayTag 为键保存监听者列表。广播时,若监听者使用 PartialMatch,子系统会沿 Tag 的父级逐层向上匹配——广播 A.B.C 时,监听 A.B 的人也能收到。
K2_BroadcastMessage 的 Message 参数声明为 const int32&,但借助 CustomStructureParam 与 CustomThunk,它在蓝图里是一个可以接任意结构体的通配针脚。真正的类型在 exec 函数里从栈上取出,见 FIG. 2-3。
DEFINE_FUNCTION(UGameplayMessageSubsystem::execK2_BroadcastMessage)
{
P_GET_STRUCT(FGameplayTag, Channel);
Stack.MostRecentPropertyAddress = nullptr;
Stack.StepCompiledIn<FStructProperty>(nullptr);
void* MessagePtr = Stack.MostRecentPropertyAddress;
FStructProperty* StructProp = CastField<FStructProperty>(Stack.MostRecentProperty);
P_FINISH;
if (ensure(StructProp && StructProp->Struct && MessagePtr))
{
P_THIS->BroadcastMessageInternal(Channel, StructProp->Struct, MessagePtr);
}
}- 1LINE 05单步执行蓝图栈,取到通配参数的地址与属性。
- 2LINE 07从 FStructProperty 上读出真实的 UScriptStruct。
- 3LINE 08P_FINISH:参数读取结束,必须在执行逻辑之前。
异步节点 ASYNC ACTION
蓝图侧的监听由 UAsyncAction_ListenForGameplayMessage 完成。它是一个 UCancellableAsyncAction:激活时向子系统注册 Listener,收到消息后通过 OnMessageReceived 委托通知蓝图,取消时注销。
委托只携带 ProxyObject 与 ActualChannel,并不直接携带消息体——委托签名无法是“任意结构体”。于是插件提供 GetPayload 函数,同样用 CustomThunk 把缓存的消息拷贝到通配输出上(原理同 §2.3)。
GetPayload 只能在 OnMessageReceived 回调内调用;离开回调后,缓存的消息指针已失效。针脚优化 PINS
前文 §3.2 提到 ProxyObject 在蓝图中并不需要,所以我们可以隐藏掉,然后再创建一个名为 Payload 的输出节点来直接传具体的消息体,这样就不用再自己手动调用 GetPayload 函数。
实现位于编辑器模块的 UK2Node_AsyncAction_ListenForGameplayMessages:在 AllocateDefaultPins 中追加 Payload 针脚,ExpandNode 时生成一个中间 GetPayload 节点,并把连线搬过去。
// 生成中间节点 GetPayload
UK2Node_CallFunction* GetPayloadNode = CompilerContext.SpawnIntermediateNode<UK2Node_CallFunction>(this, SourceGraph);
GetPayloadNode->FunctionReference.SetExternalMember(TEXT("GetPayload"), ProxyClass);
GetPayloadNode->AllocateDefaultPins();
bIsErrorFree &= Schema->TryCreateConnection(LastThenPin, GetPayloadExecPin);
// Hook up the actual channel connection
UEdGraphPin* OutActualChannelPin = GetOutputChannelPin();
bIsErrorFree &= CompilerContext.MovePinLinksToIntermediate(*OutActualChannelPin, *ActualChannelVar.TempVar->GetVariablePin()).CanSafeConnect();- 1LINE 02编译期生成中间节点——运行时并不存在,没有额外开销。
- 2LINE 08把外部连线搬到中间节点的针脚上。
小结 SUMMARY
运行时用 Subsystem + CustomThunk 解决“任意结构体”的传递,编辑器用自定义 K2Node 把复杂度藏起来。最终,蓝图用户只看到一个干净的节点。