Course contentsShow
← Unreal Engine Game Development
Lesson 228 of 8804. Advanced Input and PhysicsFree lesson

Implementing Enhanced Input Subsystems

You will learn to register and activate specific Input Mapping Contexts for your player character using the Enhanced Input Local Player Subsystem.

In this lesson, you will learn how to programmatically register and activate UInputMappingContext assets at runtime using the UEnhancedInputLocalPlayerSubsystem.

Why the Subsystem Matters

While we have defined our UInputAction and UInputMappingContext (IMC) assets in the editor, these assets are just static data until they are pushed into the active input system. The UEnhancedInputLocalPlayerSubsystem acts as the manager for the current player's input stack. By interacting with this subsystem, we can dynamically add or remove mappings, allowing for contextual gameplay—like swapping a "Driving" mapping context for a "Walking" one the moment a player enters a vehicle.

The Implementation Pattern

To activate a context, we first need to retrieve the subsystem from the ULocalPlayer. Once we have a reference, we use AddMappingContext to register our IMC asset.

Here is how you would typically implement this in your APawn or ACharacter class:

#include "EnhancedInputSubsystems.h"
#include "EnhancedInputComponent.h"

void AMyCharacter::BeginPlay()
{
    Super::BeginPlay();

    // 1. Get the local player controller
    if (APlayerController* PC = Cast<APlayerController>(GetController()))
    {
        // 2. Retrieve the Enhanced Input Local Player Subsystem
        if (UEnhancedInputLocalPlayerSubsystem* Subsystem = 
            ULocalPlayer::GetSubsystem<UEnhancedInputLocalPlayerSubsystem>(PC->GetLocalPlayer()))
        {
            // 3. Add the mapping context with a priority (higher numbers override lower ones)
            if (DefaultMappingContext)
            {
                Subsystem->AddMappingContext(DefaultMappingContext, 0);
            }
        }
    }
}

Key Considerations

  • The Priority Argument: The second parameter in AddMappingContext is an integer representing priority. If you have two different contexts that define the same input key (e.g., Spacebar for "Jump" and Spacebar for "Deploy Parachute"), the one with the higher priority value will be evaluated first.
  • Safety: Always ensure your UInputMappingContext* property is assigned in the editor before calling AddMappingContext, or the system will fail silently.
  • Cleanup: In more advanced scenarios, you can use RemoveMappingContext to clean up your input stack when the player exits a specific state, keeping your input processing lean.

Key Takeaway: The UEnhancedInputLocalPlayerSubsystem is the gateway that bridges your static input data assets to the active player, allowing you to control exactly which input mappings are live at any given moment.