数据驱动的按键重映射

给玩家做"自定义按键"的最小实现。

数据结构

USTRUCT(BlueprintType)
struct FKeyBindingEntry
{
    UPROPERTY(EditAnywhere) UInputAction* Action;
    UPROPERTY(EditAnywhere) FKey Key;          // 按键
    UPROPERTY(EditAnywhere) FKey Key2;         // 第二键(手柄)
};

存档: TArray<FKeyBindingEntry> 序列化到 SaveGame。

应用:运行时改 IMC

void ApplyBindings(UInputMappingContext* Ctx, const TArray<FKeyBindingEntry>& Bindings)
{
    for (const FKeyBindingEntry& E : Bindings)
    {
        for (FEnhancedActionKeyMapping& M : Ctx->Map)
        {
            if (M.Action == E.Action) { M.Key = E.Key; break; }   // 改第一个映射
        }
    }
    // 重新添加以生效
    Subsystem->RemoveMappingContext(Ctx);
    Subsystem->AddMappingContext(Ctx, Priority);
}

工程上推荐运行时从原始 IMC "复制"一个实例来改:

UInputMappingContext* Live = DuplicateObject(IMC_Default, GetTransientPackage());

不改原资产、退出恢复默认、避免误存盘。

UI 的按键提示自动更新

重映射后,按键提示文本/图标查 QueryKeysMappedToAction 自动刷新。配合"按键等待绑定"的 UI(按任意键捕获键值):用 Button + 监听任意按键事件。

本章小结

  • 重映射 = 改 IMC 的 Map(建议改 Duplicate 出的运行时副本)+ Remove/Add 刷新。
  • 存档用"动作 → 键"的结构体数组。
  • 按键提示用 Query API 自动同步。