#[TIP] Simpler Enhanced Input setup

1 messages · Page 1 of 1 (latest)

boreal robin
#

Something I that disliked about the enhanced input system was having to individually bind each action, and add UInputActions for each action, and then initialize the actions in your blueprint. Seemed like a lot of redundant busy work when the mapping context contained all this information. I came across an easier solution in ALS that I thought I'd share. You set up your mapping context and match the button press functions names to the IA_* mapping and that's it. Far less bookkeeping. Here's the code:

void AProPlayerController::SetupInputComponent()
{
    Super::SetupInputComponent();

    UEnhancedInputComponent* EnhancedInputComponent = Cast<UEnhancedInputComponent>(InputComponent);
    if (EnhancedInputComponent)
    {
        EnhancedInputComponent->ClearActionEventBindings();
        EnhancedInputComponent->ClearActionValueBindings();
        EnhancedInputComponent->ClearDebugKeyBindings();

        BindActions(DefaultInputMappingContext);
        BindActions(DebugInputMappingContext);
    }
    else
    {
        UE_LOG(LogTemp, Fatal, TEXT("We require Enhanced Input System to be activated in project settings to function properly"));
    }
}
#
void AProPlayerController::BindActions(UInputMappingContext* Context)
{
    if (Context)
    {
        const TArray<FEnhancedActionKeyMapping>& Mappings = Context->GetMappings();
        UEnhancedInputComponent* EnhancedInputComponent = Cast<UEnhancedInputComponent>(InputComponent);
        if (EnhancedInputComponent)
        {
            // There may be more than one keymapping assigned to one action. So, first filter duplicate action entries to prevent multiple delegate bindings
            TSet<const UInputAction*> UniqueActions;
            for (const FEnhancedActionKeyMapping& Keymapping : Mappings)
            {
                UniqueActions.Add(Keymapping.Action);
            }

            for (const UInputAction* UniqueAction : UniqueActions)
            {
                EnhancedInputComponent->BindAction(UniqueAction, ETriggerEvent::Triggered, Cast<UObject>(this), UniqueAction->GetFName());
            }
        }
    }
}

void AProPlayerController::SetupInputs()
{
    if (PossessedCharacter)
    {
        if (UEnhancedInputLocalPlayerSubsystem* Subsystem = ULocalPlayer::GetSubsystem<UEnhancedInputLocalPlayerSubsystem>(GetLocalPlayer()))
        {
            FModifyContextOptions Options;
            Options.bForceImmediately = 1;
            Subsystem->AddMappingContext(DefaultInputMappingContext, 1, Options);
        }
    }
}

void AProPlayerController::IA_Move(const FInputActionValue& Value)
{
    if (PossessedCharacter)
    {
        PossessedCharacter->Move(Value.Get<FVector2D>());
    }
}