In this lesson, you will learn how to layer multiple Input Mapping Contexts (IMCs) to create a sophisticated control scheme that shifts dynamically based on your game’s state.
The Concept of Input Stacking
Think of Input Mapping Contexts as transparent overlays on your game. You don't have to swap them out entirely; instead, you can stack them. When multiple contexts are active, Unreal’s Enhanced Input Subsystem evaluates them based on their Priority. If two contexts bind the same key to different actions, the one with the higher priority wins.
This is essential for gameplay states. For example, your "Character Movement" context might have a priority of 0. When you open a pause menu, you add a "Menu Navigation" context with a priority of 1. Because the menu context has higher priority, the game will ignore the character movement keys and prioritize your menu logic, preventing your character from running around while you are trying to select an option.
Implementing Context Switching
To manage this, you retrieve the UEnhancedInputLocalPlayerSubsystem and use AddMappingContext or RemoveMappingContext. You should store references to your UInputMappingContext assets as UPROPERTY pointers in your Character or PlayerController class.
// Add the menu context with a higher priority (e.g., 1)
if (UEnhancedInputLocalPlayerSubsystem* Subsystem = ULocalPlayer::GetSubsystem<UEnhancedInputLocalPlayerSubsystem>(PC->GetLocalPlayer()))
{
Subsystem->AddMappingContext(MenuMappingContext, 1);
}
// Remove it when the menu is closed to revert control to the lower priority context
Subsystem->RemoveMappingContext(MenuMappingContext);
Why Order Matters
When you stack contexts, you are creating a "Input Priority Hierarchy." By managing these dynamically, you ensure your input system is reactive. Always remember to remove a context when it is no longer relevant to avoid "input leakage," where a hidden menu might still be consuming controller signals. By using AddMappingContext with a specific priority integer, you create a robust, modular input architecture that scales well as your game grows.
Key Takeaway: Use the Priority integer when adding mapping contexts to create a layered input stack, ensuring high-priority interfaces take precedence over standard gameplay movement.