GameFeatures Plugin in Unreal Engine

Words: 1851

Core Concepts and Origins

GameFeature is a framework introduced in UE5 that supports dynamically loading gameplay. It uses a plugin-based architecture to deliver “plug-and-play” modular game features. Epic developed this framework to address the following challenges faced by modern games (especially live-service games):

  • Frequent content updates: e.g., seasonal content rotation in Fortnite, requiring dynamic addition/removal of game features
  • Parallel development needs: new features can be developed in parallel with the current version without breaking the core game
  • Hot-plug capability: dynamically enable/disable features at runtime without repackaging the entire game

You can read Modular Gameplay Plugins in Unreal Engine together with this plugin.

System Architecture and Core Components

  graph TD
    A[UGameFeaturesSubsystem<br/>全局管理器] --> B[UGameFeaturePluginStateMachine<br/>状态机]
    B --> C[EGameFeaturePluginState<br/>状态枚举]
    A --> D[UGameFeatureData<br/>数据配置]
    D --> E[UGameFeatureAction<br/>动作列表]
    E --> F[AddComponent/AddWidget<br/>具体Action实现]
    
    A --> G[UGameFeaturesProjectPolicies<br/>策略控制]
    G --> H[Load/Client/Server模式]
    
    F --> I[UGameFrameworkComponentManager<br/>组件管理]
    I --> J[Receiver注册机制]

Core Class Responsibilities

Class NameInheritanceResponsibility
UGameFeaturesSubsystemUEngineSubsystemGlobal singleton; manages the lifecycle of all GameFeatures and provides external APIs
UGameFeaturePluginStateMachineUObjectOne State Machine per GameFeature; handles state transitions
UGameFeatureDataUPrimaryDataAssetConfiguration asset; defines the list of Actions to execute for this GameFeature
UGameFeatureActionUObjectBase class for actions; defines operations executed at specific lifecycle stages
UGameFeaturesProjectPoliciesUObjectPolicy class; controls loading rules (Client/Server/editor environments)
UGameFrameworkComponentManagerUGameInstanceSubsystemComponent management system; handles dynamic AddComponent

Lifecycle State Machine

The GameFeature lifecycle is strictly managed by a State Machine. Each GameFeaturePlugin corresponds to a UGameFeaturePluginStateMachine instance, stored in UGameFeaturesSubsystem::GameFeaturePluginStateMachines (TMap<FString, StateMachine>).

Core State Definitions

  stateDiagram-v2
    [*] --> Installed: 发现插件
    Installed --> Registered: Load/Register
    Registered --> Loaded: 预加载资源
    Loaded --> Active: Activate
    Active --> Loaded: Deactivate
    Loaded --> Registered: Unload
    Registered --> Installed: Unregister
    
    Active --> [*]: Terminal(释放内存)
    Installed --> [*]: Terminal
    
    note right of Active
        完全激活状态
        Actions正在执行
        对游戏产生影响
    end note
    
    note left of Installed
        仅在硬盘上存在
        Content浏览器不可见
    end note

Detailed State Description

StateEnglish IdentifierDescriptionAsset Visibility
InstalledInstalledPlugin is in local storage and not yet registered with AssetManager❌ Not shown in Content
RegisteredRegisteredPlugin assets are known and scanned into AssetManager but not yet loaded✅ Browsable but not loaded
LoadedLoadedPlugin loaded into memory, registered in the game but not activated✅ Loaded
ActiveActiveFully activated; Actions are executing and affecting Gameplay✅ Running

State Transition API

cpp
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
// UGameFeaturesSubsystem提供的外部控制接口
void LoadGameFeaturePlugin(const FString& PluginURL, CompleteDelegate);
void LoadAndActivateGameFeaturePlugin(const FString& PluginURL, CompleteDelegate);
void DeactivateGameFeaturePlugin(const FString& PluginURL, CompleteDelegate);
void UnloadGameFeaturePlugin(const FString& PluginURL, CompleteDelegate);
void ReleaseGameFeaturePlugin(const FString& PluginURL, CompleteDelegate);
void UninstallGameFeaturePlugin(const FString& PluginURL, CompleteDelegate);
void TerminateGameFeaturePlugin(const FString& PluginURL, CompleteDelegate);

// 目标状态枚举(简化操作)
enum class EGameFeatureTargetState : uint8
{
    Installed,    // 仅安装
    Registered,   // 注册到AssetManager
    Loaded,       // 加载到内存
    Active        // 完全激活
};

State Machine Internal Implementation

State transitions are implemented through ChangeGameFeatureDestination:

cpp
1
2
3
4
5
void UGameFeaturesSubsystem::ChangeGameFeatureDestination(
    UGameFeaturePluginStateMachine* Machine,
    const FGameFeaturePluginStateRange& StateRange,
    FGameFeaturePluginChangeStateComplete CompleteDelegate
);

Each state inherits from FGameFeaturePluginState and includes:

  • BeginState(): called when entering the state
  • UpdateState(): updates every frame (checks conditions to advance to the next state)
  • TryCancelState(): attempts to cancel the current state
  • EndState(): called when leaving the state

Transitional States: There are intermediate transition states between states (such as Registering, Loading, Activating, etc.) used to handle asynchronous asset loading.


Hands-on: Creating Your First GameFeature

Prerequisites: Enable Required Plugins

Two plugins must be enabled at the same time:

  1. GameFeatures: implements Action execution and GameFeature loading
  2. ModularGameplay: provides implementation support for AddComponent

Path: 编辑(Edit) → 插件(Plugins) → search and enable

Step 1: Create a GameFeature Plugin

  1. Open the Plugins window and click + 新建插件
  2. Select the Game Feature (with C++) Template
  3. Name the plugin (e.g., MyBattleFeature)
  4. ⚠️ Key constraint: Do not change the default directory; it must be placed under Plugins/GameFeatures! The source code hard-codes detection of only this directory

Automatically generated after creation:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
Plugins/GameFeatures/MyBattleFeature/
├── Content/
│   └── MyBattleFeature.uasset    ← GameFeatureData(必须保持同名)
├── Resources/
│   └── Icon128.png
├── Source/
│   └── MyBattleFeatureRuntime/
│       ├── MyBattleFeatureRuntime.Build.cs
│       ├── Public/MyBattleFeatureRuntimeModule.h
│       └── Private/MyBattleFeatureRuntimeModule.cpp
└── MyBattleFeature.uplugin

⚠️ Key constraint: The GameFeatureData asset name must exactly match the plugin name!

Step 2: Configure AssetManager

Automatic configuration: Creating a GameFeature through the editor automatically configures AssetManager.

Manual configuration (if copying a GameFeature from elsewhere):

  1. Open 项目设置(Project Settings) → Asset Manager
  2. Add a Primary Asset Type:
    • Primary Asset Type: GameFeatureData
    • Asset Base Class: GameFeatureData
    • Directories: Add the Plugins/GameFeatures/ path

⚠️ Required configuration: GameFeature strongly relies on AssetManager’s asset discovery mechanism. If not configured, a warning will appear when the editor starts, and it will not work properly.

Step 3: Configure Actions

Double-click MyBattleFeature.uasset to open the configuration panel:

SettingDescription
Initial StateDefault target state when the editor starts
Current StateCurrent actual state (switched at runtime)
ActionsArray of actions to execute when this GameFeature is activated

Common Built-in Actions

Action TypeFunctionUse Case
AddComponentDynamically add a component to a specified Actor classAdd ability components, animation components
AddWidgetAdd a UI widget to the HUDAdd health bars, minimap
AddDataRegistryAdd a data registryConfiguration table extension
AddGameplayCueAdd a GameplayCueVFX extension

Configuration example (AddComponent):

  • Actor Class: ACharacter (target Actor base class)
  • Component Class: UMyBattleSkillComponent (component to add)
  • Server/Client: choose server-only, client-only, or both

⚠️ Note: In the Active state, the Edit Plugin button cannot be clicked. After editing GameFeatureData, change Current State to Installed and then back to Active to reload, or simply restart the editor.

Step 4: Register the Actor as a Receiver

For AddComponent to take effect, the target Actor must be registered as a Receiver:

cpp
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
void AMyCharacter::BeginPlay()
{
    Super::BeginPlay();
    
    // 注册为GameFeature Receiver
    UGameFrameworkComponentManager::AddReceiver(this);
}

void AMyCharacter::EndPlay(const EEndPlayReason::Type EndPlayReason)
{
    // 必须配对移除,避免内存泄漏
    UGameFrameworkComponentManager::RemoveReceiver(this);
    
    Super::EndPlay(EndPlayReason);
}

⚠️ Key constraint: Forgetting to call AddReceiver is the most common issue during debugging—the Action is configured but the Actor does not respond!

Simplified approach: Inherit from the base classes provided by ModularGameplayActors, which already have Receiver registration built in:

  • AModularCharacter
  • AModularPlayerController
  • AModularGameState
  • AModularGameMode
  • etc…

Step 5: Activate at Runtime

Editor Method

Directly switch the Current State slider in the GameFeatureData asset panel: Installed → Registered → Loaded → Active

C++ Runtime API

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
// 获取PluginURL(通过插件名)
FString PluginURL;
UGameFeaturesSubsystem::Get().GetPluginURLByName(FString("MyBattleFeature"), PluginURL);

// 方式1:加载并激活(异步)
UGameFeaturesSubsystem::Get().LoadAndActivateGameFeaturePlugin(
    PluginURL,
    FGameFeaturePluginLoadComplete::CreateLambda([](const UE::GameFeatures::FResult& Result)
    {
        if (Result.HasError())
        {
            UE_LOG(LogTemp, Error, TEXT("激活失败: %s"), *Result.GetError());
        }
        else
        {
            UE_LOG(LogTemp, Log, TEXT("激活成功!"));
        }
    })
);

// 方式2:指定目标状态(更灵活)
UGameFeaturesSubsystem::Get().ChangeGameFeatureTargetState(
    PluginURL,
    EGameFeatureTargetState::Active,  // 或 Installed/Registered/Loaded
    CompleteDelegate
);

⚠️ Note: Result.GetError() returns an empty string on success; printing it directly may cause a crash. Check Result.HasError() first.

Console Commands (Debug)

1
2
3
4
GameFeaturePlugin.Activate MyBattleFeature
GameFeaturePlugin.Deactivate MyBattleFeature
GameFeaturePlugin.Load MyBattleFeature
GameFeaturePlugin.Unload MyBattleFeature

Deep Dive into Core Mechanisms

How AddComponent Works

  sequenceDiagram
    participant GFCM as GameFrameworkComponentManager
    participant GF as GameFeature
    
    目标Actor->>GFCM: AddReceiver(this)
    GFCM->>GFCM: 添加到Receiver列表
    
    GF->>GFCM: AddComponentRequest(ActorClass, ComponentClass)
    GFCM->>GFCM: RequestTrackingMap[Key]++ (引用计数)
    
    alt Actor已初始化
        GFCM->>目标Actor: CreateComponentOnInstance()
        GFCM->>GFCM: ComponentClassToComponentInstanceMap[ComponentClass].Add(Instance)
    else Actor未生成
        GFCM->>GFCM: 等待Actor生成时再创建
    end
    
    GF->>GFCM: RemoveComponentRequest() (Deactivate时)
    GFCM->>GFCM: RequestTrackingMap[Key]--
    
    alt 引用计数==0
        GFCM->>GFCM: 查找ComponentClassToComponentInstanceMap
        GFCM->>目标Actor: 销毁该Component的所有Instance
    end

Reference Counting Mechanism: Multiple GameFeatures can request the same ComponentClass to be added to the same ActorClass, and the lifecycle is managed through reference counting.

Deferred Registration Support: Even after a GameFeature is already activated, if a new Actor calls AddReceiver later, it can immediately receive the ExtensionAdded event and have components created.

ExtensionHandler Mechanism (Non-Component Extensions)

Used to listen for Actor lifecycle events instead of directly adding components:

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
// 在GameFeatureAction中注册ExtensionHandler
TSharedPtr<FComponentRequestHandle> ExtensionRequestHandle = 
    ComponentManager->AddExtensionHandler(
        HUDActorClass,  // 监听的Actor类
        UGameFrameworkComponentManager::FExtensionHandlerDelegate::CreateUObject(
            this, 
            &ThisClass::HandleActorExtension,
            ChangeContext
        )
    );

void HandleActorExtension(AActor* Actor, FName EventName, FGameFeatureStateChangeContext ChangeContext)
{
    if (EventName == UGameFrameworkComponentManager::NAME_ExtensionAdded ||
        EventName == UGameFrameworkComponentManager::NAME_GameActorReady)
    {
        // Actor准备就绪,执行自定义逻辑(如添加UI)
        AddWidgets(Actor);
    }
    else if (EventName == UGameFrameworkComponentManager::NAME_ExtensionRemoved ||
             EventName == UGameFrameworkComponentManager::NAME_ReceiverRemoved)
    {
        // Actor被移除,清理资源
        RemoveWidgets(Actor);
    }
}

Asset Loading Flow

In the Registered state, based on PrimaryAssetTypesToScan configured in GameFeatureData:

cpp
1
2
3
4
5
6
7
void UGameFeaturesSubsystem::AddGameFeatureToAssetManager(const UGameFeatureData* GameFeatureToAdd)
{
    // 1. 检查资源是否存在
    // 2. 扫描指定PrimaryAssetType
    // 3. 注册到AssetManager的扫描路径
    // 4. 异步加载所需Bundle
}

In the Unregistering state, RemoveGameFeatureFromAssetManager is executed in reverse to unload assets.


Advanced Usage and Extensions

Custom GameFeatureAction

Inherit from UGameFeatureAction to implement custom logic:

cpp
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
UCLASS(MinimalAPI, meta = (DisplayName = "Add My Custom System"))
class UGameFeatureAction_AddMySystem : public UGameFeatureAction
{
    GENERATED_BODY()
    
public:
    // 配置属性
    UPROPERTY(EditAnywhere, Category=Settings)
    TSoftClassPtr<UMySystem> SystemClass;
    
    // 生命周期回调
    virtual void OnGameFeatureRegistering(...) override;
    virtual void OnGameFeatureActivating(...) override;
    virtual void OnGameFeatureDeactivating(...) override;
    virtual void OnGameFeatureUnregistering(...) override;
};

Custom ProjectPolicies

Create a policy class to control loading rules (e.g., load different GameFeatures on Client/Server):

cpp
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
UCLASS(Config=Game)
class MYGAME_API UMyGameFeaturePolicy : public UGameFeaturesProjectPolicies
{
    GENERATED_BODY()
    
public:
    virtual void InitGameFeatureManager() override;
    virtual void GetGameFeatureLoadingMode(bool& bLoadClientData, bool& bLoadServerData) const override;
    virtual bool IsPluginAllowed(const FString& PluginURL) const override;
};

Configuration path: 项目设置 → GameFeatures → Game Features Manager Class

Lyra Project Best Practices

The Lyra sample project demonstrates production-grade usage of GameFeature:

UI Extension Pattern:

cpp
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// GameFeatureAction_AddWidgets 示例
void AddToWorld(const FWorldContext& WorldContext, const FGameFeatureStateChangeContext& ChangeContext)
{
    if (UGameFrameworkComponentManager* ComponentManager = 
        UGameInstance::GetSubsystem<UGameFrameworkComponentManager>(GameInstance))
    {
        // 注册ExtensionHandler而非直接AddComponent
        TSharedPtr<FComponentRequestHandle> ExtensionRequestHandle = 
            ComponentManager->AddExtensionHandler(
                ALyraHUD::StaticClass(),
                FExtensionHandlerDelegate::CreateUObject(this, &ThisClass::HandleActorExtension, ChangeContext)
            );
    }
}

void HandleActorExtension(AActor* Actor, FName EventName, ...)
{
    if (EventName == UGameFrameworkComponentManager::NAME_GameActorReady)
    {
        // 向CommonUI的LayerStack推入Widget
        UCommonUIExtensions::PushContentToLayer_ForPlayer(LocalPlayer, LayerID, WidgetClass);
    }
}

Common Issues and Debugging Tips

Must-Check List

SymptomPossible CauseSolution
GameFeature not shown in ContentNot in the Plugins/GameFeatures directoryMove the plugin to the correct directory
AssetManager errorGameFeatureData scan path not configuredCheck AssetManager settings
AddComponent does not respondActor did not call AddReceiverAdd Receiver registration in BeginPlay
Validation fails after renaming BlueprintGameFeature references the old name (UE5.1 Bug)Recompile + save, or roll back to 5.0.3
Runtime loading failsIncorrect PluginURLUse GetPluginURLByName to get the correct URL
Callback crashCalling Result.GetError() on successCheck Result.HasError() first

Debug Commands

cpp
1
2
3
4
5
6
7
// 控制台
GameFeatures.List          // 列出所有GameFeature状态
GameFeatures.Activate [Name]
GameFeatures.Deactivate [Name]

// C++调试
UGameFeaturesSubsystem::Get().DumpGameFeatureState();  // 打印状态机详情

Best Practices Summary

  1. Directory structure: Strictly keep the Plugins/GameFeatures/ path and do not change the GameFeatureData name
  2. State management: Understand State Machine transitions and avoid editing configuration in the Active state
  3. Receiver registration: All Actors that need dynamically added Components must properly register/remove the Receiver
  4. Asset management: Configure PrimaryAssetType scanning reasonably to avoid loading unnecessary assets
  5. Network compatibility: Use GetGameFeatureLoadingMode to distinguish Client/Server loading policies
  6. Version Control: GameFeature plugins should be under independent Version Control to facilitate parallel development and hot updates
  7. Error handling: In asynchronous API callbacks, always check Result.HasError() before accessing error information

With the GameFeature framework, truly modular and service-oriented game development can be achieved, making the technical implementation of “Games as a Service” (GaaS) practical and feasible.

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...