I was trying to implement the enhanced input in C++, and I found that the code provided by UE documentation is not working, but this code from other sources works well.
Could somebody enlighten me, why the documentation does not work while this one works? I really appreciate your time and explanation.
How does it is not working?
- no error
- It’s just the UE log is not triggered which indicates the related code is not running as well.
UE Documentation:
// Expose a mapping context as a property in your header file...
UPROPERTY(EditAnywhere, Category="Input")
TSoftObjectPtr<UInputMappingContext> InputMapping;
// In your cpp...
if (ULocalPlayer* LocalPlayer = Cast<ULocalPlayer>(Player))
{
if (UEnhancedInputLocalPlayerSubsystem* InputSystem = LocalPlayer->GetSubsystem<UEnhancedInputLocalPlayerSubsystem>())
{
if (!InputMapping.IsNull())
{
InputSystem->AddMappingContext(InputMapping.LoadSynchronous(), Priority);
}
}
}
My cpp
// my cpp
if (ULocalPlayer* LocalPlayer = Cast<ULocalPlayer>(GetController()))
{
UE_LOG(LogTemp, Display, TEXT("Init: Local Player found!"));
if (UEnhancedInputLocalPlayerSubsystem* InputSystem = LocalPlayer->GetSubsystem<UEnhancedInputLocalPlayerSubsystem>())
{
if (!InputMapping.IsNull())
{
UE_LOG(LogTemp, Display, TEXT("Init: Adding Mapping Context!"));
InputSystem->AddMappingContext(InputMapping.LoadSynchronous(), 0);
}
}
}
Other sources: (link)
// header
UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Enhanced Input")
class UInputMappingContext* InputMapping;
// cpp
void AInputExampleCharacter::SetupPlayerInputComponent(class UInputComponent* PlayerInputComponent)
{
// Get the player controller
APlayerController* PC = Cast<APlayerController>(GetController());
// Get the local player subsystem
UEnhancedInputLocalPlayerSubsystem* Subsystem = ULocalPlayer::GetSubsystem<UEnhancedInputLocalPlayerSubsystem>(PC->GetLocalPlayer());
// Clear out existing mapping, and add our mapping
Subsystem->ClearAllMappings();
Subsystem->AddMappingContext(InputMapping, 0);
}