Of course! Let's break down how to use the InjectInputForAction function from Unreal Engine's Enhanced Input system.
Conceptual Overview
What is InjectInputForAction?
This function allows you to programmatically simulate or fake player input. Instead of waiting for the player to press a key, move the mouse, or use a controller, you can call this function to tell the Enhanced Input system, "Pretend the player just performed this action with this value."
Why would you use it?
This is not for handling normal player input. It's for special cases, such as:
- Automated Testing: You can write a test that makes a character jump, move, and fire without any human interaction to verify that game logic works correctly.
- AI-Controlled Pawns: You can have an AI character use the exact same input action system as the player. Instead of calling
AddMovementInput directly, the AI's behavior tree could decide to "move forward" and inject that input, triggering all the same logic a player would.
- Tutorials: Forcing a player action during a tutorial. For example, "The game will now demonstrate a jump," and the character jumps on its own.
- Replays / Ghost Cars: Replaying a saved sequence of inputs to perfectly recreate a player's actions.
Function Parameters Explained
const UInputAction* Action: A pointer to the Input Action asset you want to trigger (e.g., IA_Jump, IA_Move). You must create these in the Content Browser first.
FInputActionValue RawValue: The value of the input. The type of this value depends on the Value Type you set in the Input Action asset:
Digital (bool): FInputActionValue(true) or FInputActionValue(false). Used for things like Jump or Interact.
Axis1D (float): FInputActionValue(0.75f). Used for things like throttle or leaning.
Axis2D (FVector2D): FInputActionValue(FVector2D(1.0f, 0.5f)). Used for standard movement.
Axis3D (FVector): FInputActionValue(FVector(0.0f, 0.0f, 10.0f)). Used for 6-DOF movement (e.g., in space sims).
const TArray<UInputModifier*>& Modifiers: An optional list of Input Modifiers to apply to this injection only. This can override the modifiers defined on the action asset.
const TArray<UInputTrigger*>& Triggers: An optional list of Input Triggers to apply to this injection only.
Note on AutoCreateRefTerm: The Meta=(AutoCreateRefTerm="...") specifier is a C++ convenience. It means you can pass an empty initializer list {} for the Modifiers and Triggers TArrays, and the compiler will automatically create a temporary, empty TArray for you. This makes the function call much cleaner.
C++ Example: Simulating a Jump
Let's create a simple scenario: We have a character that can jump when the player presses the spacebar. We will also add a C++ function that we can call (for example, via a console command) to make the character jump programmatically.
1. Setup in the Unreal Editor
Before writing code, you need the necessary assets.
- Enable Plugin: Make sure the Enhanced Input plugin is enabled (
Edit > Plugins).
- Create Input Action: In the Content Browser, right-click and create
Input > Input Action. Name it IA_Jump.
- Open
IA_Jump and set its Value Type to Digital (bool).
- Create Input Mapping Context: Right-click and create
Input > Input Mapping Context. Name it IMC_Default.
- Open
IMC_Default, click the + next to Mappings, and add IA_Jump.
- Click the keyboard icon next to
IA_Jump and select the Space Bar.
2. C++ Character Header (.h file)
Here, we'll set up properties for our input assets and declare the functions for both normal input handling and input injection.
// MyCharacter.h
#pragma once
#include "CoreMinimal.h"
#include "GameFramework/Character.h"
#include "InputActionValue.h" // Required for FInputActionValue
#include "MyCharacter.generated.h"
// Forward declare classes
class UInputMappingContext;
class UInputAction;
UCLASS()
class MYPROJECT_API AMyCharacter : public ACharacter
{
GENERATED_BODY()
public:
AMyCharacter();
protected:
virtual void BeginPlay() override;
public:
// Called to bind functionality to input
virtual void SetupPlayerInputComponent(class UInputComponent* PlayerInputComponent) override;
// --- INPUT ASSETS ---
UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Enhanced Input")
UInputMappingContext* DefaultMappingContext;
UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Enhanced Input")
UInputAction* JumpAction;
// --- INPUT HANDLERS ---
// These functions are called by REAL player input
void HandleJump(const FInputActionValue& Value);
// --- INPUT INJECTION ---
// This is our example function to inject input
UFUNCTION(Exec) // 'Exec' makes this function a console command for easy testing
void SimulateJump();
};
3. C++ Character Source (.cpp file)
Here we implement the logic. We'll bind IA_Jump to our HandleJump function. Then, in SimulateJump, we'll get the input component and call InjectInputForAction.
// MyCharacter.cpp
#include "MyCharacter.h"
#include "EnhancedInputSubsystems.h" // Required for the subsystem
#include "EnhancedInputComponent.h" // Required for casting UInputComponent
#include "Components/InputComponent.h"
#include "GameFramework/PlayerController.h"
AMyCharacter::AMyCharacter()
{
PrimaryActorTick.bCanEverTick = true;
}
void AMyCharacter::BeginPlay()
{
Super::BeginPlay();
// Make sure we have a valid PlayerController
if (APlayerController* PlayerController = Cast<APlayerController>(GetController()))
{
// Get the Enhanced Input subsystem
if (UEnhancedInputLocalPlayerSubsystem* Subsystem = ULocalPlayer::GetSubsystem<UEnhancedInputLocalPlayerSubsystem>(PlayerController->GetLocalPlayer()))
{
// Add our mapping context
Subsystem->AddMappingContext(DefaultMappingContext, 0);
}
}
}
void AMyCharacter::SetupPlayerInputComponent(UInputComponent* PlayerInputComponent)
{
Super::SetupPlayerInputComponent(PlayerInputComponent);
// Cast the InputComponent to UEnhancedInputComponent
if (UEnhancedInputComponent* EnhancedInputComponent = Cast<UEnhancedInputComponent>(PlayerInputComponent))
{
// Bind the JumpAction to our handler function
// This handles REAL input from the player (e.g., pressing Space Bar)
if (JumpAction)
{
EnhancedInputComponent->BindAction(JumpAction, ETriggerEvent::Triggered, this, &AMyCharacter::HandleJump);
}
}
}
// This function is triggered by the REAL player input
void AMyCharacter::HandleJump(const FInputActionValue& Value)
{
// The value is a bool because IA_Jump is Digital (bool)
const bool bIsJumping = Value.Get<bool>();
if (bIsJumping)
{
UE_LOG(LogTemp, Warning, TEXT("HandleJump: Real jump input received!"));
ACharacter::Jump();
}
}
// This is our function that SIMULATES the input
void AMyCharacter::SimulateJump()
{
// Get the Player's Input Component, which is where the injection function lives.
// It must be cast to the Enhanced version.
if (UEnhancedInputComponent* EnhancedInputComponent = Cast<UEnhancedInputComponent>(PlayerInputComponent))
{
// Make sure we have a valid action to inject
if (JumpAction)
{
UE_LOG(LogTemp, Warning, TEXT("SimulateJump: Injecting jump input..."));
// This is the core of the example!
// We inject the 'JumpAction' with a 'true' value.
// We pass empty {} for Modifiers and Triggers because we don't need custom ones.
FInputActionValue InjectionValue(true);
EnhancedInputComponent->InjectInputForAction(JumpAction, InjectionValue, {}, {});
}
}
else
{
UE_LOG(LogTemp, Error, TEXT("SimulateJump: Could not find an Enhanced Input Component on the player."));
}
}
4. Final Setup and Testing
-
Compile your C++ code.
-
In the Unreal Editor, create a Blueprint based on your AMyCharacter C++ class.
-
Open the Blueprint and in the Details Panel, assign your IMC_Default and IA_Jump assets to the corresponding properties.
-
In your Game Mode, set this new Blueprint as the Default Pawn Class.
-
Press Play.
To Test:
- Normal Input: Press the Space Bar. Your character should jump, and you'll see the "Real jump input received!" message in the Output Log.
- Injected Input:
- Open the console by pressing the tilde (
~) key.
- Type
SimulateJump and press Enter.
- Your character should jump, and you'll see the "Injecting jump input..." message in the log, followed by the "Real jump input received!" message. This proves that the injected action was successfully processed through the exact same system as the real input.