Using IConsoleCommand in UE5
Another way to create a custom console command in UE5 using C++ is by using IConsoleCommand.

Game Engine
Unreal Engine 5.5.3
IDE
Rider 2024.3.5
Project Name
MyProject
OS
macOS Sequoia 15.3
This is the third post in creating custom console commands in Unreal Engine 5. In the previous two posts, one creates a command using the Exec function specifier while the other onse usesFAutoConsoleCommandWithWorldAndArgs function. This post will create a custom console command using IConsoleCommand
.
Inside the MyCheatManager
constructer create a variable with the IConsoleCommand
type and we start the var with IConsoleManager::Get().RegisterConsoleCommand
. The RegisterConsoleCommand
takes four parameters, I'll list them below, directly taken from the IConsoleCommand.h
file in the Unreal code base.
- Name - The name of this command (must not be nullptr)
- Help - Help text for this command
- Command - The user function to call when this command is executed
- Flags - Optional flags bitmask
First, we need to create a new static function in the header, I called mine MyCommandFunction
. We'll define in the .cpp
file and then we'll reference in the third argument via FConsoleCommandWithWorldAndArgsDelegate::CreateLambda. The
MyCommandFunction` method is very simple, it just prints a string.
The following link is a wonderful community snippet for registering a console command, it includes a great way to unregister the console command when it's no longer needed.
MyCheatManager.h
#pragma once
#include "CoreMinimal.h"
#include "GameFramework/CheatManager.h"
#include "MyCheatManager.generated.h"
UCLASS()
class MYPROJECT_API UMyCheatManager : public UCheatManager
{
GENERATED_BODY()
UMyCheatManager();
UFUNCTION(Exec)
void GetPlayerName();
UFUNCTION()
static void MyCommandFunction(const TArray<FString>& Args, UWorld* World);
};
MyCheatManager.cpp
#include "MyCheatManager.h"
#include "MyProject/TP_ThirdPerson/TP_ThirdPersonCharacter.h"
UMyCheatManager::UMyCheatManager()
{
static IConsoleCommand* MyConsleCommand = IConsoleManager::Get().RegisterConsoleCommand(
TEXT("MyCheatManager.PrintCommand"),
TEXT("Print a simle string from the MyCheatManager"),
FConsoleCommandWithWorldAndArgsDelegate::CreateLambda(&UMyCheatManager::MyCommandFunction),
ECVF_Cheat
);
}
...
void UMyCheatManager::MyCommandFunction(const TArray<FString>& Args, UWorld* World)
{
if (GEngine)
{
GEngine->AddOnScreenDebugMessage(-1, 105.f, FColor::Green, TEXT("IConsole Command"));
}
}
After recompiling the project we can now use the new console command. While playing in the editor or another debug build, press the tilde ~
key to open the command line then type in MyCheatManager.PrintCommand
(or your command's name) and you'll get a message printed on the screen.

There's definitely a variety of ways to create custom console commands in Unreal and I'm looking forward to using them in the future.

Harrison McGuire