You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Unreal Engine中如何获取Input Action引用以绑定Pawn类按键方法?

解决Unreal中Enhanced Input动作绑定"identifier 'MyAction' is undefined"错误

核心原因

直接在代码里写MyAction无效——蓝图输入映射上下文里创建的动作,必须在C++类中通过UPROPERTY声明变量,才能让引擎识别并关联蓝图里的动作资源。另外你代码里存在函数名不匹配的问题:绑定的MyActionTriggered未定义,实际写的回调函数是MyActionPressed,需要统一。

解决步骤

1. 修改FirstPawn.h头文件

引入Enhanced Input相关头文件,并声明用于关联蓝图动作的变量:

#pragma once

#include "CoreMinimal.h"
#include "Pawn.h"
// 引入Enhanced Input必要头文件
#include "EnhancedInputComponent.h"
#include "EnhancedInputSubsystems.h"
#include "FirstPawn.generated.h"

UCLASS()
class YOURPROJECT_API AFirstPawn : public APawn
{
    GENERATED_BODY()

public:
    AFirstPawn();

protected:
    virtual void BeginPlay() override;

public:
    virtual void Tick(float DeltaTime) override;
    virtual void SetupPlayerInputComponent(class UInputComponent* PlayerInputComponent) override;

    // 声明可在蓝图中赋值的Input Action变量
    UPROPERTY(EditAnywhere, Category = "Input")
    UInputAction* MyAction;

    // 动作触发的回调函数
    UFUNCTION()
    void MyActionPressed();
};

2. 修正FirstPawn.cpp中的绑定代码

修正动作引用和函数名,添加空指针检查避免崩溃:

#include "FirstPawn.h"

AFirstPawn::AFirstPawn()
{
    PrimaryActorTick.bCanEverTick = true;
}

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

    // 可选:若未在其他地方激活输入映射上下文,添加这段激活IMC_my
    if (APlayerController* PlayerController = Cast<APlayerController>(GetController()))
    {
        if (UEnhancedInputLocalPlayerSubsystem* Subsystem = ULocalPlayer::GetSubsystem<UEnhancedInputLocalPlayerSubsystem>(PlayerController->GetLocalPlayer()))
        {
            // 替换为你的IMC_my资源路径(右键IMC_my选Copy Reference粘贴此处)
            Subsystem->AddMappingContext(LoadObject<UInputMappingContext>(nullptr, TEXT("/Game/YourPath/IMC_my.IMC_my")), 0);
        }
    }
}

void AFirstPawn::MyActionPressed()
{
    UE_LOG(LogTemp, Warning, TEXT("WOOHOO"));
}

void AFirstPawn::Tick(float DeltaTime)
{
    Super::Tick(DeltaTime);
}

void AFirstPawn::SetupPlayerInputComponent(UInputComponent* PlayerInputComponent)
{
    UEnhancedInputComponent* Input = Cast<UEnhancedInputComponent>(PlayerInputComponent);
    if (Input && MyAction)
    {
        // 根据需求选择触发事件:Started对应按下瞬间,Triggered对应按住持续触发
        Input->BindAction(MyAction, ETriggerEvent::Started, this, &AFirstPawn::MyActionPressed);
    }
}

3. 蓝图中关联动作

编译代码后,打开FirstPawn蓝图(无蓝图则创建),在细节面板的Input分类下,将MyAction变量选择为你在IMC_my中创建的动作。

内容的提问来源于stack exchange,提问作者manidos

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 02:22:43