【UE4/UE5】在虚幻引擎中创建控制台指令的几种方法
大家好,我是key。
在使用 Unreal Engine 做开发的时候,我们经常需要一些“隐藏指令”来调试,比如快速生成一个物体、打印日志、或者修改某些运行参数。UE 本身就支持自定义 控制台指令(Console Command),而且方式不止一种。下面我总结了几种常见做法,大家可以根据需求来选。
1. 使用 FAutoConsoleCommand
这是最常见、最简单的方式,写一个全局变量就能自动注册。
比如我们用指令“MyGame.Hello"来演示,
#include "Engine/Engine.h"
#include "HAL/IConsoleManager.h"// 简单指令
static FAutoConsoleCommand MyTestCommand(TEXT("MyGame.Hello"), //命令TEXT("Print a hello message"), //描述FConsoleCommandDelegate::CreateLambda([](){if (GEngine){GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Green, TEXT("Hello from console!"));}})
);// 带 World 的指令
static FAutoConsoleCommandWithWorld MyWorldCommand(TEXT("MyGame.SpawnCube"), //如上TEXT("Spawn a cube in world"),FConsoleCommandWithWorldDelegate::CreateLambda([](UWorld* World){if (World){World->SpawnActor<AActor>(AActor::StaticClass(), FVector::ZeroVector, FRotator::ZeroRotator);}})
);
用法:在控制台输入
MyGame.Hello MyGame.SpawnCube
2. 使用 IConsoleManager::RegisterConsoleCommand
如果你是写插件或者模块,通常会在 StartupModule()
里注册指令。
// 在模块 StartupModule 里
IConsoleManager::Get().RegisterConsoleCommand(TEXT("MyGame.DynamicCommand"),TEXT("Dynamic command example"),FConsoleCommandDelegate::CreateRaw(this, &FMyModule::MyCommandHandler),ECVF_Default
);
3. Exec 函数
在某些类里(比如 PlayerController、GameInstance)你可以重写 Exec
,自己解析指令。
bool AMyPlayerController::Exec(UWorld* InWorld, const TCHAR* Cmd, FOutputDevice& Ar)
{if (FParse::Command(&Cmd, TEXT("MyCustomCommand"))){UE_LOG(LogTemp, Log, TEXT("MyCustomCommand executed!"));return true;}return Super::Exec(InWorld, Cmd, Ar);
}
输入:
MyCustomCommand
4. CheatManager + UFUNCTION(exec)
这是最常见的“作弊指令”写法,非常适合快速调试。
UCLASS()
class UMyCheatManager : public UCheatManager
{GENERATED_BODY()public:UFUNCTION(exec)void KillAllEnemies(){UE_LOG(LogTemp, Log, TEXT("All enemies killed!"));}
};
控制台输入:
KillAllEnemies
5. 蓝图里用 exec
如果你写蓝图函数的时候加上 UFUNCTION(exec)
,同样能在控制台调用。不过这一点大多数人不太常用,一般还是在 C++ 里写比较方便。
总结
-
全局/快速调试 →
FAutoConsoleCommand
-
模块/插件 →
IConsoleManager::RegisterConsoleCommand
-
类内扩展 → 重写
Exec
-
作弊/调试命令 →
CheatManager + exec