Modular Gameplay Plugin in Unreal Engine

Words: 3483

Plugin Overview

The Modular Gameplay plugin is a framework in Unreal Engine for implementing Gameplay. Its core is to provide an extensible gameplay framework while making initialization states easier to handle.

You can read this together with GameFeatures plugin in Unreal Engine to understand this plugin.

Core Positioning and Architecture

The Game Framework Component Manager is a Game Instance Subsystem in the Modular Gameplay plugin. It is designed specifically to work with Game Feature Plugins, providing extensible Gameplay infrastructure.

  graph TD
    A[GameInstance] --> B[Game Framework Component Manager]
    B --> C[Extension Handlers System]
    B --> D[Initialization States System]
    C --> E[Actor Receivers]
    C --> F[Extension Handlers]
    D --> G[Actor Features]
    D --> H[Init States]
    
    style A fill:#2d2d2d,stroke:#fff,stroke-width:2px,color:#fff
    style B fill:#1a472a,stroke:#4ade80,stroke-width:2px,color:#fff
    style C fill:#1e3a8a,stroke:#60a5fa,stroke-width:2px,color:#fff
    style D fill:#7c2d12,stroke:#fb923c,stroke-width:2px,color:#fff

Extension Handlers System

This system allows dynamic modification of game objects when a game feature is activated, without hard-coded dependencies. It consists of two complementary parts:

Receivers - Actors Being Extended

Any Actor that wants to be extended must follow a specific registration lifecycle:

Registration timing: In PreInitializeComponents(), call AddGameFrameworkComponentReceiver() Unregistration timing: In EndPlay(), call RemoveGameFrameworkComponentReceiver()

cpp
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
// 典型实现模式(基于Lyra的AModularCharacter)
void AMyModularActor::PreInitializeComponents()
{
    Super::PreInitializeComponents();
    // 确保在正常组件初始化流程中注册
    UGameFrameworkComponentManager::AddGameFrameworkComponentReceiver(this);
}

void AMyModularActor::EndPlay(const EEndPlayReason::Type EndPlayReason)
{
    // 确保在Actor销毁或禁用时清理
    UGameFrameworkComponentManager::RemoveGameFrameworkComponentReceiver(this);
    Super::EndPlay(EndPlayReason);
}

Sending custom events: A receiver can call SendGameFrameworkComponentExtensionEvent(FName EventName) at any time to send an arbitrary event. These events are stateless and only affect currently active handlers.

Extension Handlers - Extenders

There are two registration methods:

Method 1: Manual Delegate Registration

Call AddExtensionHandler(FName ExtensionEventName, FGameFrameworkComponentDelegate Delegate); suitable for scenarios that require fine-grained control over logic.

Method 2: Component Request Wrapper

Call AddComponentRequest(const FGameFrameworkComponentRequest& Request) to automatically add the required component.

Key constraint: The handles returned by both registration methods (FGameFrameworkComponentReceiverHandle or FGameFrameworkComponentRequestHandle) must be stored like an array. A delegate remains registered only if a live shared pointer reference to the returned handle struct exists.

cpp
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
// 句柄存储示例(在GameFeatureAction中)
TArray<FGameFrameworkComponentReceiverHandle> ExtensionHandles;
TArray<FGameFrameworkComponentRequestHandle> ComponentRequests;

void UMyGameFeatureAction::OnGameFeatureActivating()
{
    auto& Manager = UGameInstance::GetSubsystem<UGameFrameworkComponentManager>(GetGameInstance());
    
    // 方式一:手动处理程序
    ExtensionHandles.Add(Manager->AddExtensionHandler(
        NAME_ExtensionAdded,
        FGameFrameworkComponentDelegate::CreateUObject(this, &UMyGameFeatureAction::HandleExtension)
    ));
    
    // 方式二:组件请求
    FGameFrameworkComponentRequest Request;
    Request.ReceiverClass = AMyCharacter::StaticClass();
    Request.ComponentClass = UMyFeatureComponent::StaticClass();
    ComponentRequests.Add(Manager->AddComponentRequest(Request));
}

Practical Use in Lyra

Component/ClassRoleImplementation Details
ALyraCharacterReceiverInherits from AModularCharacter and handles registration automatically
LyraHUDManual callerManually calls extension functions to enable UI extension
ShooterCore (GFP)Component adderUses UGameFeatureAction_AddComponents to add components in batches
UGameFeatureAction_AddInputBindingCustom actionRegisters manual handlers to respond to multiple events

Input binding example: The HandlePawnExtension function responds to the following events:

  • NAME_ExtensionRemoved / NAME_ExtensionAdded: Triggered when a handler is added/removed
  • NAME_BindInputsNow: A specific game event emitted by LyraHeroComponent, used to bind feature-specific input

Initialization States System

Design Philosophy

The Initialization States system (abbreviated as Init State) is used to track the lifecycle and initialization progress of different features on an Actor, especially to handle complex synchronization problems in network replication scenarios.

Core constraints:

  • States are globally defined (the whole game shares the same set of state definitions)
  • The state sequence is linear (from creation to full initialization)
  • It is not a general-purpose State Machine (not suitable for arbitrary Gameplay state transitions)
  flowchart LR
    A[Spawning] --> B[DataAvailable]
    B --> C[DataInitialized]
    C --> D[GameplayReady]
    
    style A fill:#dc2626,stroke:#fff,color:#fff
    style B fill:#ea580c,stroke:#fff,color:#fff
    style C fill:#ca8a04,stroke:#fff,color:#fff
    style D fill:#16a34a,stroke:#fff,color:#fff

Core Concepts

Actor Features

  • Definition: A unique feature identifier (FName) registered on an Actor
  • Implementation: Usually a component, but it can also be any Gameplay object
  • Naming: Can be a native class name or a feature name (e.g. "HeroComponent", "PawnExtension")

State Tracking Mechanism

The system maintains the following for each feature of each Actor:

  1. Current init state (Init State)
  2. Implementing object (usually a component instance)

For objects implementing IGameFrameworkInitStateInterface, the feature name is returned by the GetFeatureName() interface function.

State Registration and Management

State Registration

States are implemented as Gameplay Tags and must be registered during game instance initialization via RegisterInitState(FGameplayTag State).

Registration order is state order, for example:

cpp
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
// ULyraGameInstance::Init() 中的注册示例
void ULyraGameInstance::Init()
{
    Super::Init();
    
    auto& Manager = GetSubsystem<UGameFrameworkComponentManager>();
    
    // 按顺序注册状态
    Manager->RegisterInitState(LyraGameplayTags::InitState_Spawned);
    Manager->RegisterInitState(LyraGameplayTags::InitState_DataAvailable);
    Manager->RegisterInitState(LyraGameGameplayTags::InitState_DataInitialized);
    Manager->RegisterInitState(LyraGameplayTags::InitState_GameplayReady);
}

Core Interface Functions (IGameFrameworkInitStateInterface)

FunctionPurposeImplementation Notes
CanChangeInitState(FGameplayTag NewState)Validate state transitionChecks whether required data is available; returns true to allow the transition
HandleChangeInitState(FGameplayTag NewState)Execute state transitionPerforms object-specific changes for that state
CheckDefaultInitialization()Advance initialization chainCalls ContinueInitStateChain to automatically advance states in array order

Registration and Query API

FunctionPurposeWhen to Call
RegisterInitStateFeature()Register a feature with the systemComponent OnRegister()
UnregisterInitStateFeature()Unregister from the systemEndPlay()
HasReachedInitState(FName FeatureName, FGameplayTag State)Query whether a specific feature has reached a stateAny coordination logic
HaveAllFeaturesReachedInitState(FGameplayTag State)Query whether all features on an Actor have reached a stateCentral coordinator waiting on dependencies

State Change Notification System

The system provides a powerful delegate registration mechanism:

Listening for a Specific Actor

RegisterAndCallForActorInitState(AActor* Actor, FName FeatureName, FGameplayTag State, FActorInitStateChangedDelegate Delegate)

Behavior: If the feature is already in the specified state, the delegate executes immediately.

Listening Globally for a Class

RegisterAndCallForClassInitState(TSubclassOf<AActor> ActorClass, FName FeatureName, FGameplayTag State, ...)

Suitable for listening to global initialization events (e.g. “when all Hero components are ready…”).

Convenience Interface Functions

  • BindOnActorInitStateChanged(): Quickly listen for state changes of other features on the same Actor
  • OnActorInitStateChanged(): Callback function; usually calls CheckDefaultInitialization() internally to advance its own state

Delegate execution behavior: Designed to handle multiple state transitions occurring in succession; all relevant delegates will be called.


Analysis of Lyra’s Complete Initialization Flow

Lyra uses a 4-state system to solve complex initialization race conditions in network replication:

StateDefinitionTrigger Timing
InitState.SpawnedSpawning and initial replication completeWhen BeginPlay() is called
InitState.DataAvailableAll required data has been replicated/loadedAfter dependent data is ready
InitState.DataInitializedData initialization operations completeFor example, after Gameplay abilities are added
InitState.GameplayReadyFully initialized and interactableAfter all systems are ready

Core Coordination Components

  graph TB
    subgraph Actor["LyraCharacter (Receiver)"]
        PEC[ULyraPawnExtensionComponent<br/>协调总体初始化]
        HC[ULyraHeroComponent<br/>处理摄像机/输入初始化]
        ASC[LyraAbilitySystemComponent]
    end
    
    subgraph External["跨Actor依赖"]
        PS[LyraPlayerState<br/>慢速复制数据]
        PC[PlayerController]
        PD[PawnData]
    end
    
    PEC -.->|等待| PS
    PEC -.->|等待| PC
    PEC -.->|等待| PD
    HC -.->|等待| PS
    HC -.->|等待| InputComp
    
    style PEC fill:#1e40af,stroke:#60a5fa,color:#fff
    style HC fill:#701a75,stroke:#e879f9,color:#fff

Detailed Timeline

Phase 1: Spawning and Registration (All Clients)

  1. Component attachment and registration: When the character is spawned, all components (including LyraPawnExtensionComponent, LyraHeroComponent, and LyraAbilitySystemComponent) are attached
  2. Feature registration: From OnRegister(), each component calls RegisterInitStateFeature() to declare its existence to the manager

Phase 2: BeginPlay Divergence

  • Server: BeginPlay() is called immediately
  • Client: Called only after all replicated properties have sent initial data (timing varies with the amount of component data)

Phase 3: Initialization Startup (Spawned State)

In BeginPlay():

  1. Call BindOnActorInitStateChanged() to listen for state changes of other features
  2. Call CheckDefaultInitialization() to try to advance the state chain
  3. All components first reach InitState.Spawned

Phase 4: Data Availability Check (DataAvailable Race)

When the Hero component tries to enter DataAvailable:

  • Check condition: Whether PlayerState and InputComponent are ready
  • If not ready: The State Machine pauses and waits for subsequent CheckDefaultInitialization() calls
  • If ready: Enters DataAvailable, but cannot immediately enter DataInitialized

When the Pawn extension component tries to enter DataAvailable:

  • Check condition: Whether PawnData and Controller are fully available
  • From multiple OnRep functions (such as OnRep_Controller and OnRep_PawnData), call CheckDefaultInitialization() to advance the state after reference replication completes

Phase 5: Coordinated Advancement (DataInitialized Synchronization)

When the Pawn extension component tries to enter DataInitialized:

  • Blocking condition: Check whether all other components (such as the Hero component) have reached DataAvailable
  • Coordination mechanism: Wait using HaveAllFeaturesReachedInitState(InitState_DataAvailable)
  • Trigger chain: Once the condition is met, the Pawn extension component enters DataInitialized and notifies the Hero component via OnActorInitStateChanged to also advance to DataInitialized
  • Key operation: During this transition, Gameplay abilities are created and bound to player input

Phase 6: Fully Ready (GameplayReady)

  • The Hero component and Pawn extension component successively enter InitState.GameplayReady
  • Blueprint callback trigger: UI classes such as W_Nameplate previously registered listeners for this state via RegisterAndCallForActorInitState, and now execute their initialization logic

Comparison of Race Condition Solutions

Traditional ApproachInitialization States System Approach
Random delay loop (SetTimer polling)State-driven, precise notifications
Complex nested OnRep logicUnified state query interface
Hard-to-track initialization dependenciesExplicit HaveAllFeaturesReachedInitState checks
Difficult client/server divergence handlingAutomatically adapts to differences in BeginPlay call timing

Best Practices Summary

Receiver Implementation Checklist

  • Inherit from a base class that supports Modular Gameplay (such as AModularCharacter) or implement registration manually
  • In PreInitializeComponents, call AddGameFrameworkComponentReceiver
  • In EndPlay, call RemoveGameFrameworkComponentReceiver
  • Avoid hard-coding dependencies on extension components in the receiver

Extension Handler Implementation Checklist

  • Use TArray to persistently store returned handles
  • Ensure handles are cleared in OnGameFeatureDeactivating (automatically unbinding delegates)
  • For component addition, prefer AddComponentRequest over manual NewObject

Initialization State Implementation Checklist

  • Components inherit IGameFrameworkInitStateInterface
  • In OnRegister, call RegisterInitStateFeature
  • In EndPlay, call UnregisterInitStateFeature
  • Override CanChangeInitState to implement strict transition condition checks
  • Override HandleChangeInitState to execute state-specific side effects (such as adding abilities)
  • In OnRep functions, call CheckDefaultInitialization to advance the State Machine
  • Use BindOnActorInitStateChanged to listen for the readiness of dependent features

State Design Principles

  1. Linear progression: States should be ordered chronologically and avoid going backward
  2. Explicit dependencies: CanChangeInitState for each state should explicitly list all prerequisites
  3. Central coordination: For complex Actors, designate a “main coordinator component” (such as PawnExtensionComponent) to use HaveAllFeaturesReachedInitState to synchronize other components
  4. Immediate callback: Use the “execute immediately if already reached” behavior of the RegisterAndCallFor family of functions to handle late-join scenarios

Q&A

I will supplement the Q&A section for specific applications based on the official documentation and common development scenarios, helping readers use this system correctly in actual development.


Game Framework Component Manager Application Q&A Guide

Extension Handlers System in Practice

Q1: When should I use extension handlers instead of hard-coding components directly in the Actor?

Scenarios for using extension handlers:

  • The feature is an optional module (such as a seasonal event or DLC content)
  • Gameplay features that need hot-plugging (dynamically loaded via Game Feature Plugin)
  • General features reused across projects (such as input systems or quest systems)
  • You do not want to introduce too many dependencies into the base character class

Scenarios for hard-coding components:

  • Core gameplay mechanics (such as health components or basic movement)
  • Features that all characters must have
  • Extremely performance-sensitive scenarios (avoid dynamic lookup overhead)
  flowchart TD
    A{功能是否可选?} -->|是| B{是否跨项目复用?}
    A -->|否| C[硬编码组件]
    B -->|是| D[GameFeatureAction + 扩展处理程序]
    B -->|否| E{需要热插拔?}
    E -->|是| D
    E -->|否| F[Actor Component手动Add]
    
    style D fill:#16a34a,stroke:#fff,color:#fff
    style C fill:#dc2626,stroke:#fff,color:#fff

Q2: How should I correctly handle the lifecycle of extension handlers? Why does my delegate stop working after switching Levels?

Common pitfall: The returned handle is not stored persistently, causing the delegate to be garbage collected.

Correct pattern:

cpp
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
// ❌ 错误:临时变量,函数结束后句柄销毁,委托立即失效
void UMyGameFeatureAction::OnGameFeatureActivating()
{
    auto& Manager = UGameInstance::GetSubsystem<UGameFrameworkComponentManager>(GetGameInstance());
    Manager->AddExtensionHandler(NAME_ExtensionAdded, MyDelegate); // 危险!
}

// ✅ 正确:使用成员变量数组存储
UPROPERTY()
TArray<FGameFrameworkComponentReceiverHandle> ExtensionHandles;

void UMyGameFeatureAction::OnGameFeatureActivating()
{
    auto& Manager = UGameInstance::GetSubsystem<UGameFrameworkComponentManager>(GetGameInstance());
    ExtensionHandles.Add(Manager->AddExtensionHandler(NAME_ExtensionAdded, MyDelegate));
}

// ✅ 正确:在停用时清理(可选,但推荐)
void UMyGameFeatureAction::OnGameFeatureDeactivating()
{
    ExtensionHandles.Empty(); // 句柄销毁自动解除委托绑定
}

Key principle: FGameFrameworkComponentReceiverHandle holds a shared pointer internally; the delegate remains registered only while a strong reference exists.


Q3: How can a GameFeatureAction affect only a specific type of Actor (e.g. add components only to player characters, not NPCs)?

Solution: In FGameFrameworkComponentRequest, specify ReceiverClass:

cpp
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
void UMyGameFeatureAction::AddToPlayerCharactersOnly()
{
    auto& Manager = GetGameInstance()->GetSubsystem<UGameFrameworkComponentManager>();
    
    FGameFrameworkComponentRequest Request;
    // 只匹配ALyraCharacter及其子类
    Request.ReceiverClass = ALyraCharacter::StaticClass();
    Request.ComponentClass = UMyPlayerFeatureComponent::StaticClass();
    
    // 可选:使用Predicate进行更复杂的过滤
    Request.Prerequisite = [](const AActor* Actor) -> bool {
        if (const ALyraCharacter* Character = Cast<ALyraCharacter>(Actor))
        {
            // 只给拥有PlayerState的角色添加(排除AI)
            return Character->GetPlayerState() != nullptr;
        }
        return false;
    };
    
    ComponentRequests.Add(Manager->AddComponentRequest(Request));
}

Advanced technique: Use AddExtensionHandler with manual checks to make runtime dynamic decisions:

cpp
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
void UMyConditionalFeature::HandleExtension(AActor* Receiver, const FGameFrameworkComponentDelegate& Delegate)
{
    // 检查是否满足特定条件(如角色等级、游戏模式等)
    if (IsValid(Receiver) && ShouldApplyToActor(Receiver))
    {
        // 动态创建组件或执行逻辑
        UMyFeatureComponent* Comp = NewObject<UMyFeatureComponent>(Receiver);
        Comp->RegisterComponent();
    }
}

Q4: What is the difference between an Extension Event and an Init State? When should I use which?

FeatureExtension EventInit State
StatefulnessStateless, instantaneousStateful, persistent
PurposeNotify that something happenedTrack progress/readiness
Listening methodRegister a delegateRegister a delegate + query current state
Typical scenario“Input now needs binding”, “UI needs refresh”“Data is ready”, “Gameplay can start”
Immediate executionNo (only triggered by new events)Yes (executes immediately on registration if already reached)

Decision flow:

  flowchart LR
    A{需要知道<br/>当前进度吗?} -->|是| B[使用初始化状态系统]
    A -->|否| C{是一次性通知<br/>还是持续变化?}
    C -->|一次性| D[使用扩展事件]
    C -->|需跟踪历史| B
    D --> E[如: BindInputsNow<br/>RefreshUI]
    B --> F[如: DataAvailable<br/>GameplayReady]
    
    style B fill:#1e40af,stroke:#60a5fa,color:#fff
    style D fill:#701a75,stroke:#e879f9,color:#fff

Practical example (Lyra input binding):

cpp
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
// 扩展事件:通知"现在该绑定了"(瞬发)
void ULyraHeroComponent::OnPawnReadyToBindInput()
{
    // 发送事件给所有监听者
    FGameFrameworkComponentDelegate Delegate;
    Delegate.BindUObject(this, &ULyraHeroComponent::BindInput);
    SendGameFrameworkComponentExtensionEvent(NAME_BindInputsNow);
}

// 初始化状态:标记"输入系统已完全就绪"(持久状态)
void ULyraHeroComponent::OnInputBindingsComplete()
{
    // 更新状态,其他系统可查询
    ContinueInitStateChain({InitState_DataInitialized, InitState_GameplayReady});
}

Initialization States System in Practice

Q5: My component depends on PlayerState data, but PlayerState replicates slowly. How can I avoid race conditions?

Problem scenario:

cpp
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
// ❌ 危险:假设PlayerState在BeginPlay时已就绪
void UMyComponent::BeginPlay()
{
    Super::BeginPlay();
    if (ALyraPlayerState* PS = GetPlayerState<ALyraPlayerState>())
    {
        AbilitySystemComponent = PS->GetLyraAbilitySystemComponent(); // 可能为nullptr!
        InitializeAbilities(); // 崩溃或初始化失败
    }
}

Solution: Use the Initialization States system for coordination

cpp
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
UCLASS()
class MYGAME_API UMyComponent : public UActorComponent, public IGameFrameworkInitStateInterface
{
    GENERATED_BODY()
    
public:
    virtual FName GetFeatureName() const override { return FName("MyFeature"); }
    virtual bool CanChangeInitState(UGameFrameworkComponentManager* Manager, FGameplayTag NewState) const override;
    virtual void HandleChangeInitState(UGameFrameworkComponentManager* Manager, FGameplayTag NewState) override;
    virtual void CheckDefaultInitialization() override;
    
protected:
    virtual void OnRegister() override;
    virtual void BeginPlay() override;
    virtual void EndPlay(const EEndPlayReason::Type EndPlayReason) override;
    
    // 监听PlayerState的就绪状态
    void OnPlayerStateReady(AActor* Actor, FName FeatureName, FName AffectedFeature, FGameplayTag PreviousState, FGameplayTag NewState);
};

void UMyComponent::OnRegister()
{
    Super::OnRegister();
    RegisterInitStateFeature(); // 声明存在
}

void UMyComponent::BeginPlay()
{
    Super::BeginPlay();
    
    // 监听PlayerState的DataAvailable状态
    BindOnActorInitStateChanged(FName("HeroComponent"), LyraGameplayTags::InitState_DataAvailable,
        FActorInitStateChangedDelegate::CreateUObject(this, &UMyComponent::OnPlayerStateReady));
    
    CheckDefaultInitialization(); // 尝试推进
}

bool UMyComponent::CanChangeInitState(UGameFrameworkComponentManager* Manager, FGameplayTag NewState) const
{
    if (NewState == LyraGameplayTags::InitState_DataAvailable)
    {
        // 关键:显式检查依赖是否就绪
        if (!Manager->HasReachedInitState(GetOwner(), FName("HeroComponent"), LyraGameplayTags::InitState_DataAvailable))
        {
            return false; // 等待HeroComponent就绪
        }
        
        // 检查具体数据
        if (ALyraPlayerState* PS = GetPlayerState<ALyraPlayerState>())
        {
            return PS->GetLyraAbilitySystemComponent() != nullptr;
        }
        return false;
    }
    return true;
}

void UMyComponent::OnPlayerStateReady(AActor* Actor, FName FeatureName, FName AffectedFeature, FGameplayTag PreviousState, FGameplayTag NewState)
{
    // 依赖就绪,尝试推进自身状态
    CheckDefaultInitialization();
}

Q6: How do I design a “central coordinator” component to manage initialization of a complex Actor?

Scenario: A character has multiple components (ability system, input, camera, equipment) that need to be initialized in a specific order.

Design Pattern: PawnExtensionComponent as coordinator

  sequenceDiagram
    participant P as PawnExtensionComponent<br/>(协调器)
    participant H as HeroComponent
    participant A as AbilitySystemComp
    participant E as EquipmentComponent
    
    Note over P,E: Phase 1: 各组件注册
    P->>P: RegisterInitStateFeature("PawnExtension")
    H->>H: RegisterInitStateFeature("HeroComponent")
    A->>A: RegisterInitStateFeature("AbilitySystem")
    
    Note over P,E: Phase 2: BeginPlay尝试推进
    P->>P: CheckDefaultInitialization()
    H->>H: CheckDefaultInitialization()
    
    Note over P,E: Phase 3: 协调器检查依赖
    P->>P: CanChangeInitState(DataAvailable)?
    Note right of P: 检查Controller<br/>检查PawnData
    
    P->>P: CanChangeInitState(DataInitialized)?
    Note right of P: 使用HaveAllFeaturesReachedInitState<br/>检查HeroComponent是否DataAvailable<br/>检查AbilitySystem是否DataAvailable
    
    Note over P,E: Phase 4: 协调推进
    P->>H: OnActorInitStateChanged触发
    P->>A: OnActorInitStateChanged触发
    H->>H: CheckDefaultInitialization()<br/>推进到DataInitialized
    A->>A: CheckDefaultInitialization()<br/>推进到DataInitialized
    
    P->>P: 所有依赖就绪,进入GameplayReady

Coordinator core implementation:

cpp
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
bool ULyraPawnExtensionComponent::CanChangeInitState(UGameFrameworkComponentManager* Manager, FGameplayTag NewState) const
{
    if (NewState == LyraGameplayTags::InitState_DataInitialized)
    {
        // 中央协调:等待所有其他功能达到DataAvailable
        return Manager->HaveAllFeaturesReachedInitState(GetOwner(), LyraGameplayTags::InitState_DataAvailable);
    }
    else if (NewState == LyraGameplayTags::InitState_GameplayReady)
    {
        // 等待所有功能完成DataInitialized
        return Manager->HaveAllFeaturesReachedInitState(GetOwner(), LyraGameplayTags::InitState_DataInitialized);
    }
    return true;
}

void ULyraPawnExtensionComponent::HandleChangeInitState(UGameFrameworkComponentManager* Manager, FGameplayTag NewState)
{
    if (NewState == LyraGameplayTags::InitState_DataInitialized)
    {
        // 通知所有监听者:现在可以初始化Gameplay能力了
        BroadcastOnPlayerStateReady();
    }
    else if (NewState == LyraGameplayTags::InitState_GameplayReady)
    {
        // 通知UI:角色完全就绪
        BroadcastOnPawnReady();
    }
}

Q7: What are the behavioral differences of initialization states on clients and servers? How should I handle them?

Key differences:

AspectServerClient
BeginPlay trigger timingCalled immediately after spawningCalled after initial replication completes
Data availabilityImmediately available (authoritative data)Must wait for network replication
State advancement speedFast (no waiting)Slow (depends on network latency)
Race condition riskLowHigh (must check OnRep)

Handling strategy:

cpp
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
void UMyNetworkedComponent::BeginPlay()
{
    Super::BeginPlay();
    
    // 关键:只在客户端设置复制回调来推进状态
    if (GetOwner()->GetLocalRole() != ROLE_Authority)
    {
        // 监听关键属性的复制
        if (ALyraCharacter* Character = Cast<ALyraCharacter>(GetOwner()))
        {
            Character->OnPawnDataChanged.AddUObject(this, &UMyNetworkedComponent::OnRep_PawnData);
        }
    }
    
    CheckDefaultInitialization();
}

void UMyNetworkedComponent::OnRep_PawnData()
{
    // 数据到达后,尝试推进状态机
    CheckDefaultInitialization();
}

bool UMyNetworkedComponent::CanChangeInitState(UGameFrameworkComponentManager* Manager, FGameplayTag NewState) const
{
    if (NewState == MyGameTags::InitState_DataAvailable)
    {
        // 通用检查:无论客户端还是服务器都需要的数据
        if (!GetPawnData()) return false;
        
        // 客户端额外检查:确保复制完成
        if (GetOwner()->GetLocalRole() != ROLE_Authority)
        {
            // 检查是否收到服务器确认(通过特定标记或属性)
            if (!bReceivedServerAck) return false;
        }
    }
    return true;
}

Q8: How can I use the Initialization States system without inheriting the interface? (Blueprint or legacy code compatibility)

Scenario: You need to add initialization state management to an Actor whose source cannot be modified (such as an engine class or a third-party plugin class).

Solution: Call the manager API manually

cpp
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
// C++中为非接口类包装
UCLASS()
class MYGAME_API UInitStateWrapperComponent : public UActorComponent
{
    GENERATED_BODY()
    
    // 代表的功能名称
    UPROPERTY(EditAnywhere, Category = "Init State")
    FName FeatureName = FName("WrappedFeature");
    
    virtual void OnRegister() override
    {
        Super::OnRegister();
        if (UGameFrameworkComponentManager* Manager = GetGameInstance()->GetSubsystem<UGameFrameworkComponentManager>())
        {
            // 手动注册,不通过接口
            Manager->RegisterInitStateFeature(GetOwner(), FeatureName, this);
        }
    }
    
    void SetInitState(FGameplayTag NewState)
    {
        if (UGameFrameworkComponentManager* Manager = GetGameInstance()->GetSubsystem<UGameFrameworkComponentManager>())
        {
            // 手动报告状态变更
            Manager->UpdateFeatureInitState(GetOwner(), FeatureName, NewState);
        }
    }
};

Using it in Blueprint:

Blueprint classes can directly call the Blueprint version of RegisterAndCallForActorInitState to listen for feature state changes on a specific Actor without implementing a C++ interface.


Comprehensive Scenario in Practice

Q9: How do I implement a “seasonal event” feature that adds special abilities to all players only during a specific event?

Architecture design:

  graph TB
    subgraph GFP[Game Feature Plugin: SeasonalEvent]
        A[UGameFeatureAction_AddComponents] -->|添加| B[USeasonalAbilityComponent]
        C[UGameFeatureAction_AddInputBinding] -->|绑定输入| D[特殊技能按键]
    end
    
    subgraph Game[游戏核心]
        E[ALyraCharacter] -->|作为| F[Receiver]
        G[LyraPawnExtensionComponent] -->|协调| H[初始化状态]
    end
    
    B -->|注册到| I[GameFrameworkComponentManager]
    C -->|监听| H
    
    style GFP fill:#1e3a8a,stroke:#60a5fa,color:#fff
    style Game fill:#1a472a,stroke:#4ade80,color:#fff

Implementation steps:

  1. Create a GameFeatureAction (executed when the event is activated)
  2. Use AddComponentRequest to add components to all Characters
  3. Use initialization states inside the component to ensure abilities are added only after the character is fully spawned
cpp
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
UCLASS()
class USeasonalAbilityComponent : public UActorComponent, public IGameFrameworkInitStateInterface
{
    virtual void BeginPlay() override
    {
        Super::BeginPlay();
        // 等待角色完全就绪后再添加能力,避免竞争条件
        CheckDefaultInitialization();
    }
    
    virtual bool CanChangeInitState(UGameFrameworkComponentManager* Manager, FGameplayTag NewState) const override
    {
        if (NewState == MyTags::InitState_GameplayReady)
        {
            // 确保角色已经准备好接收Gameplay能力
            return Manager->HasReachedInitState(GetOwner(), FName("HeroComponent"), 
                LyraGameplayTags::InitState_GameplayReady);
        }
        return true;
    }
    
    virtual void HandleChangeInitState(UGameFrameworkComponentManager* Manager, FGameplayTag NewState) override
    {
        if (NewState == MyTags::InitState_GameplayReady)
        {
            // 现在安全地添加赛季特殊能力
            if (UAbilitySystemComponent* ASC = GetAbilitySystemComponent())
            {
                ASC->GiveAbility(FGameplayAbilitySpec(SeasonalAbilityClass));
            }
        }
    }
};

Advantages:

  • No need to modify the base character class
  • Unloading the GFP when the event ends automatically cleans up all added components and abilities
  • Perfectly handles network replication timing issues

Q10: When debugging the Initialization States system, how can I view all feature states of the current Actor?

Debugging tips:

cpp
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
// 在控制台命令或调试UI中调用
void DebugPrintInitStates(AActor* Actor)
{
    if (!Actor) return;
    
    UGameFrameworkComponentManager* Manager = Actor->GetGameInstance()->GetSubsystem<UGameFrameworkComponentManager>();
    
    // 遍历所有注册的功能(需要Manager暴露查询接口或使用反射)
    // 实际实现可能需要添加调试函数到Manager
    
    UE_LOG(LogTemp, Log, TEXT("=== Init States for %s ==="), *Actor->GetName());
    
    // 检查特定功能
    TArray<FName> FeaturesToCheck = {FName("HeroComponent"), FName("PawnExtension"), FName("AbilitySystem")};
    for (FName Feature : FeaturesToCheck)
    {
        FGameplayTag CurrentState = Manager->GetCurrentInitState(Actor, Feature); // 假设有此API
        UE_LOG(LogTemp, Log, TEXT("Feature: %s -> State: %s"), 
            *Feature.ToString(), *CurrentState.ToString());
    }
}

Visual debugging suggestions:

  • Display debug UI above the character’s head (such as Lyra’s W_DebugInfo)
  • Use Unreal Insights to track state change timing
  • Add ensureMsgf to trigger a breakpoint on illegal state transitions

Common Errors and Solutions Quick Reference

SymptomRoot CauseSolution
Extension handler does not triggerHandle is not stored persistentlyUse a TArray<> member variable to store the returned handle
Initialization state stuck at SpawnedCanChangeInitState condition is never satisfiedCheck whether the dependency’s OnRep calls CheckDefaultInitialization
Client initialization is much slower than serverWaiting for replicated data but not listening to OnRepAdvance the State Machine in the OnRep callback
Feature reaches a state but the delegate is not triggeredUsed RegisterAndCallFor... but delegate binding failedCheck whether the delegate signature matches and ensure it is bound before registration
Features are registered repeatedly after switching LevelsEndPlay does not call UnregisterClean up in EndPlay, or ensure the component lifecycle is correct
GameFeatureAction affects the wrong Actor typeReceiverClass is set too broadlyUse a specific subclass, or add a Prerequisite predicate filter

References

This post contains some AI-assisted content, reviewed and edited by the author before publishing.
This post is licensed under CC BY-NC-SA 4.0. If it helped, or if you have anything to say, the comment box below is open.
Page views —
Unique visitors —

Loading...