- Set references to your Input Action and Input Mapping Context
- Get Enhanced Input Component
- Use
BindAction
to bind actions to functions - Register Input mapping context
//header
UPROPERTY(EditAnywhere, meta=(DisplayThumbnail=false))
UInputAction* MyAction;
UPROPERTY(EditAnywhere, meta=(DisplayThumbnail=false))
UInputMappingContext* InputMappingContext;
//cpp
void AMyCharacter::SetupPlayerInputComponent(UInputComponent* PlayerInputComponent)
{
if(UEnhancedInputComponent* EnhancedInputComponent = Cast<UEnhancedInputComponent>(PlayerInputComponent))
{
EnhancedInputComponent->BindAction(JumpAction, ETriggerEvent::Started, this, &ACharacter::Jump);
EnhancedInputComponent->BindAction(JumpAction, ETriggerEvent::Completed, this, &ACharacter::StopJumping);
EnhancedInputComponent->BindAction(MoveAction, ETriggerEvent::Triggered, this, &ThisClass::HandleMoveInput);
EnhancedInputComponent->BindAction(LookAction, ETriggerEvent::Triggered, this, &ThisClass::HandleLookInput);
//etc
}
}
void AMyCharacter::BeginPlay()
{
Super::BeginPlay();
if(APlayerController* PlayerController = Cast<APlayerController>(Controller))
{
if(UEnhancedInputLocalPlayerSubsystem* Subsystem = ULocalPlayer::GetSubsystem<UEnhancedInputLocalPlayerSubsystem>(PlayerController->GetLocalPlayer()))
{
Subsystem->AddMappingContext(InputMappingContext, 0);
}
}
}
(You need to assign values for the input actions and mapping context in a blueprint child class)
Gotchas
BindAction
does not hold a hard reference to the Input Action. This means if you don’t have a ref to the input action, it may get garbage collected, leading to your inputs no longer being handled.
This could occur for example if you load your input action from a Soft Object Pointer.
The fix is to store hard pointers to your input actions in a UPROPERTY.