Unreal Engine 5 Utilities - C++ Equivalents for Blueprint Nodes

Explore C++ implementations for common Unreal Engine 5 Blueprint nodes, covering utilities like Delay, Print String, Actor manipulation, and more. Enhance your UE5 development with these code examples.

Unreal Engine 5 Utilities

UE5 C++ Utilities: Blueprint Node Equivalents

This section provides C++ code examples for common Unreal Engine 5 utility nodes found in Blueprints. Understanding these C++ equivalents is crucial for developers who need to implement complex logic or optimize performance within their UE5 projects.

Delay Node Equivalent

There is no direct equivalent to the Blueprint Delay node in C++. Instead, timers are used to achieve similar functionality. To execute code after a specific delay, you can place that code within a function and then start a timer using Set Timer by Function Name.

Usage: Implement a function containing the delayed logic and use GetWorldTimerManager().SetTimer() to schedule its execution.

Print String Node Equivalent

The PrintString node is frequently used for debugging. In C++, you can achieve this using GEngine->AddOnScreenDebugMessage for on-screen messages or the UKismetSystemLibrary::PrintString function for more direct Blueprint-like behavior.

On-Screen Debug Message:

if (GEngine)
{
    GEngine->AddOnScreenDebugMessage(
        -1,                        // Key: -1 for unique message
        2.0f,                      // Duration: How long the message stays on screen
        FColor::Cyan,              // Color: The color of the message
        TEXT("Hello from C++!")    // Message: The string to display
    );
}

Using UKismetSystemLibrary::PrintString:

#include "Kismet/KismetSystemLibrary.h"

// In a UObject context (like an Actor or Component)
UKismetSystemLibrary::PrintString(
    this,                                    // World context object
    TEXT("Hello from KismetSystemLibrary!"), // Message
    true,                                    // Print to screen?
    true,                                    // Print to console?
    FLinearColor(0.0f, 0.66f, 1.0f, 1.0f),   // Color
    2.0f                                     // Duration
);

Get Player Controller

Retrieves the player controller for a given player index. This is essential for interacting with player input and camera.

#include "Kismet/GameplayStatics.h"

APlayerController* PlayerController = UGameplayStatics::GetPlayerController(this, 0); // 0 for the first player

Get Player Camera Manager

Accesses the camera manager associated with a specific player, allowing control over camera properties and behavior.

#include "Kismet/GameplayStatics.h"

APlayerCameraManager* PlayerCameraManager = UGameplayStatics::GetPlayerCameraManager(this, 0); // 0 for the first player

Spawn Emitter at Location

Spawns a particle system effect at a specified world location. Requires a UParticleSystem asset to be assigned.

.h File Declaration:

private:
    // Assign this UPROPERTY in the Blueprint editor
    UPROPERTY(EditAnywhere, Category = "Effects")
    UParticleSystem* ExampleEmitter;

.cpp File Implementation:

#include "Kismet/GameplayStatics.h"

UParticleSystemComponent* SpawnedEmitter;
FTransform SpawnTransform; // Define your desired spawn transform

if (ExampleEmitter)
{
    SpawnedEmitter = UGameplayStatics::SpawnEmitterAtLocation(
        GetWorld(),        // World object
        ExampleEmitter,    // The particle system asset
        SpawnTransform     // Transform where the emitter will spawn
    );
}

Line Trace By Channel

Performs a single raycast (line trace) along a specified collision channel to detect what it hits.

FVector StartLocation; // Define the start of the trace
FVector EndLocation;   // Define the end of the trace

FHitResult HitResult; // Structure to store hit information

bool bHit = GetWorld()->LineTraceSingleByChannel(
    HitResult,                                   // Output: Stores hit information
    StartLocation,                               // Start point of the trace
    EndLocation,                                 // End point of the trace
    ECollisionChannel::ECC_Visibility            // The collision channel to trace against
);

if (bHit)
{
    // Actor that was hit: HitResult.GetActor()
    // Location of the hit: HitResult.Location
}

Multi Line Trace By Channel

Performs multiple raycasts along a specified collision channel, returning all actors hit.

FVector StartLocation; // Define the start of the trace
FVector EndLocation;   // Define the end of the trace

TArray<FHitResult> HitResults; // Array to store hit information

bool bHit = GetWorld()->LineTraceMultiByChannel(
    HitResults,                                  // Output: Stores hit information for multiple hits
    StartLocation,                               // Start point of the trace
    EndLocation,                                 // End point of the trace
    ECollisionChannel::ECC_Visibility            // The collision channel to trace against
);

if (bHit)
{
    for (const FHitResult& Hit : HitResults)
    {
        // Process each hit actor: Hit.GetActor()
    }
}

Get Actor Of Class

Finds and returns the first actor of a specified class in the world. Requires a TSubclassOf<AActor> to be assigned.

.h File Declaration:

private:
    // Assign the desired Actor class in the Blueprint editor
    UPROPERTY(EditAnywhere, Category = "Actor Finding")
    TSubclassOf<AActor> ActorClassToFind;

.cpp File Implementation:

#include "Kismet/GameplayStatics.h"

AActor* FoundActor = nullptr;

if (ActorClassToFind)
{
    FoundActor = UGameplayStatics::GetActorOfClass(
        this,                               // World context object
        ActorClassToFind                    // The class of actor to search for
    );
}

if (FoundActor)
{
    // Use the found actor
}

Get All Actors Of Class

Retrieves an array containing all actors of a specified class currently present in the world.

.h File Declaration:

private:
    // Assign the desired Actor class in the Blueprint editor
    UPROPERTY(EditAnywhere, Category = "Actor Finding")
    TSubclassOf<AActor> ActorClassToFind;

.cpp File Implementation:

#include "Kismet/GameplayStatics.h"

TArray<AActor*> FoundActors;

if (ActorClassToFind)
{
    UGameplayStatics::GetAllActorsOfClass(
        this,                           // World context object
        ActorClassToFind,               // The class of actors to find
        FoundActors                     // Output: Array to store the found actors
    );
}

// Iterate through FoundActors to process each one
for (AActor* Actor : FoundActors)
{
    // Do something with each actor
}

Get All Actors With Tag

Finds all actors in the world that have a specific tag assigned to them.

#include "Kismet/GameplayStatics.h"

TArray<AActor*> ActorsWithTag;
FName TagToFind = FName("YourTag"); // Define the tag you are looking for

UGameplayStatics::GetAllActorsWithTag(
    this,                           // World context object
    TagToFind,                      // The tag name to search for
    ActorsWithTag                   // Output: Array to store actors with the tag
);

// Process the ActorsWithTag array
for (AActor* Actor : ActorsWithTag)
{
    // Actor has the specified tag
}

Spawn Actor from Class

Spawns a new actor of a specified class at a given location and rotation. Requires a TSubclassOf<AActor> to be assigned.

.h File Declaration:

private:
    // Assign the Actor class to spawn in the Blueprint editor
    UPROPERTY(EditAnywhere, Category = "Spawning")
    TSubclassOf<AActor> ActorClassToSpawn;

.cpp File Implementation:

AActor* SpawnedActor = nullptr;
FVector SpawnLocation; // Define the desired spawn location
FRotator SpawnRotation; // Define the desired spawn rotation
FActorSpawnParameters SpawnParameters; // Optional: Configure spawn parameters

if (ActorClassToSpawn)
{
    SpawnedActor = GetWorld()->SpawnActor<AActor>(
        ActorClassToSpawn,               // The class of actor to spawn
        SpawnLocation,                   // Location to spawn the actor
        SpawnRotation,                   // Rotation to spawn the actor
        SpawnParameters                  // Spawn parameters (e.g., owner, collision handling)
    );
}

if (SpawnedActor)
{
    // Actor successfully spawned
}

Play Sound 2D

Plays a sound effect that is not attached to any specific location in the world (e.g., UI sounds, background music). Requires a USoundBase asset.

.h File Declaration:

private:
    // Assign the Sound Base asset in the Blueprint editor
    UPROPERTY(EditAnywhere, Category = "Audio")
    USoundBase* SoundToPlay2D;

.cpp File Implementation:

#include "Kismet/GameplayStatics.h"

if (SoundToPlay2D)
{
    UGameplayStatics::PlaySound2D(
        this,                   // World context object
        SoundToPlay2D,          // The sound asset to play
        1.0f,                   // Volume multiplier (0.0 to 1.0)
        1.0f                    // Pitch multiplier (0.5 to 2.0)
    );
}

Play Sound at Location

Plays a sound effect originating from a specific point in the 3D world. Requires a USoundBase asset.

.h File Declaration:

private:
    // Assign the Sound Base asset in the Blueprint editor
    UPROPERTY(EditAnywhere, Category = "Audio")
    USoundBase* SoundToPlayAtLocation;

.cpp File Implementation:

#include "Kismet/GameplayStatics.h"

FVector SoundLocation; // Define the location where the sound will originate

if (SoundToPlayAtLocation)
{
    UGameplayStatics::PlaySoundAtLocation(
        this,                           // World context object
        SoundToPlayAtLocation,          // The sound asset to play
        SoundLocation,                  // The world location of the sound source
        1.0f,                           // Volume multiplier
        1.0f                            // Pitch multiplier
    );
}

Apply Damage

Applies a specified amount of damage to an actor. This function handles damage calculations and notifications.

#include "Kismet/GameplayStatics.h"

AActor* TargetActor;              // The actor to damage
AController* InstigatorController; // The controller that caused the damage
AActor* DamageCauser;             // The specific actor that caused the damage (can be self)

float DamageAmount = 100.0f;

UGameplayStatics::ApplyDamage(
    TargetActor,                  // The actor receiving damage
    DamageAmount,                 // The amount of damage to apply
    InstigatorController,         // The instigator of the damage
    DamageCauser,                 // The actor that caused the damage
    UDamageType::StaticClass()    // The damage type class (e.g., UDamageType::StaticClass() for generic damage)
);

Apply Radial Damage

Applies damage in a spherical radius around a specified location. Useful for explosions or area-of-effect attacks.

#include "Kismet/GameplayStatics.h"

FVector DamageOrigin;             // The center of the damage radius
float DamageRadius = 200.0f;      // The radius of the damage effect
AActor* DamageCauser;             // The actor that caused the damage
AController* InstigatorController; // The controller that caused the damage

UGameplayStatics::ApplyRadialDamage(
    this,                          // World context object
    100.0f,                        // Base damage amount
    DamageOrigin,                  // Center location of the damage
    DamageRadius,                  // Radius within which damage is applied
    UDamageType::StaticClass(),    // The damage type class
    TArray<AActor*>(),             // Array of actors to ignore (can be empty)
    DamageCauser,                  // The actor that caused the damage
    InstigatorController,          // The instigator of the damage
    false                          // bDoFullDamage: If true, all actors within radius take full damage
);

Get Game Mode

Retrieves the current game mode instance for the world. This is fundamental for accessing game rules and state.

#include "Kismet/GameplayStatics.h"

AGameModeBase* GameMode = UGameplayStatics::GetGameMode(this);
if (GameMode)
{
    // Cast to your specific GameMode class if needed
    // AMyGameMode* MyGameMode = Cast<AMyGameMode>(GameMode);
}

Get Game State

Retrieves the current game state instance for the world. Contains information about the current state of the game.

#include "Kismet/GameplayStatics.h"

AGameStateBase* GameState = UGameplayStatics::GetGameState(this);
if (GameState)
{
    // Cast to your specific GameState class if needed
    // AMyGameState* MyGameState = Cast<AMyGameState>(GameState);
}

Project World to Screen

Converts a 3D world coordinate into a 2D screen coordinate, useful for UI elements or overlays.

#include "Kismet/GameplayStatics.h"

APlayerController* PlayerController = UGameplayStatics::GetPlayerController(this, 0); // Get the player controller

FVector WorldPosition; // The 3D world coordinate to convert

FVector2D ScreenPosition; // Output: The resulting 2D screen coordinate

if (PlayerController)
{
    UGameplayStatics::ProjectWorldToScreen(
        PlayerController,                  // The player controller to use for projection
        WorldPosition,                     // The world position to project
        ScreenPosition,                    // Output: The calculated screen position
        false                              // bPlayerViewportRelative: If true, coordinates are relative to the player's viewport
    );
    // ScreenPosition now holds the 2D coordinates on the screen
}

Deproject Screen to World

Converts a 2D screen coordinate into a 3D world coordinate and direction. Essential for mouse interactions or placing objects based on screen input.

#include "Kismet/GameplayStatics.h"

APlayerController* PlayerController = UGameplayStatics::GetPlayerController(this, 0); // Get the player controller

FVector2D ScreenPosition; // The 2D screen coordinate to deproject

FVector WorldPosition;    // Output: The calculated 3D world position
FVector WorldDirection;   // Output: The direction from the camera through the screen point

if (PlayerController)
{
    UGameplayStatics::DeprojectScreenToWorld(
        PlayerController,                  // The player controller to use for deprojection
        ScreenPosition,                    // The screen position to deproject
        WorldPosition,                     // Output: The calculated world position
        WorldDirection                     // Output: The direction vector from the camera
    );
    // WorldPosition and WorldDirection can now be used for raycasts or placement
}

Open Level (by Name)

Loads and transitions the game to a different level. Requires the exact name of the target level.

#include "Kismet/GameplayStatics.h"

// The name of the level to open (e.g., "MyNewLevel", "ThirdPersonMap")
FName LevelNameToOpen = TEXT("ExampleMap");

UGameplayStatics::OpenLevel(
    this,                    // World context object
    LevelNameToOpen          // The name of the level to load
);

Set Game Paused

Toggles the paused state of the game. This affects gameplay simulation and ticking.

#include "Kismet/GameplayStatics.h"

bool bShouldPauseGame = true; // Set to true to pause, false to unpause

UGameplayStatics::SetGamePaused(this, bShouldPauseGame);

Spawn Decal at Location

Spawns a decal actor at a specific world location. Requires a UMaterialInterface that is set up as a decal material.

.h File Declaration:

private:
    // Assign a Decal Material in the Blueprint editor
    UPROPERTY(EditAnywhere, Category = "Decals")
    UMaterialInterface* DecalMaterial;

.cpp File Implementation:

#include "Kismet/GameplayStatics.h"

UDecalComponent* SpawnedDecalComponent = nullptr;
FVector DecalSize;       // Define the size of the decal
FVector DecalLocation;   // Define the location for the decal
FRotator DecalRotation;  // Define the rotation for the decal
float DecalLifeSpan = 0.0f; // 0.0f means the decal lasts indefinitely

if (DecalMaterial)
{
    SpawnedDecalComponent = UGameplayStatics::SpawnDecalAtLocation(
        this,                 // World context object
        DecalMaterial,        // The material to use for the decal
        DecalSize,            // The size of the decal
        DecalLocation,        // The world location to spawn the decal
        DecalRotation,        // The rotation of the decal
        DecalLifeSpan         // How long the decal should exist (0 for infinite)
    );
}

if (SpawnedDecalComponent)
{
    // Decal spawned successfully
}

Draw Debug Line

Draws a line in the world for debugging purposes. This line is visible in the editor and potentially in-game builds if enabled.

FVector LineStart; // Start point of the line
FVector LineEnd;   // End point of the line

DrawDebugLine(
    GetWorld(),        // The world object
    LineStart,         // Start point of the line
    LineEnd,           // End point of the line
    FColor::Red,       // Color of the line
    false,             // Persistent: If true, the line stays until explicitly removed
    5.0f,              // Duration: How long the line stays visible (if not persistent)
    0,                 // Depth priority: For rendering order
    1.0f               // Line thickness
);

Draw Debug Box

Draws a wireframe box in the world for debugging. Useful for visualizing collision volumes or areas.

FVector BoxCenter; // The center of the box
FVector BoxExtent; // The half-size of the box along each axis (e.g., FVector(100, 100, 100) for a 200x200x200 box)

DrawDebugBox(
    GetWorld(),        // The world object
    BoxCenter,         // Center of the box
    BoxExtent,         // Extent (half-size) of the box
    FColor::Red,       // Color of the box
    false,             // Persistent: If true, the box stays until explicitly removed
    5.0f,              // Duration: How long the box stays visible (if not persistent)
    0,                 // Depth priority: For rendering order
    1.0f               // Line thickness
);

Is Valid Check

Checks if an object pointer is valid (i.e., not null and not pending destruction). This is a fundamental safety check.

Common C++ Check:

AActor* ExampleActor = nullptr; // Assume this might be null or invalid

if (ExampleActor) // This implicitly checks if ExampleActor is not null
{
    // Actor is valid and can be used
}
else
{
    // Actor is null or invalid
}

Using UKismetSystemLibrary::IsValid (closer to Blueprint):

#include "Kismet/KismetSystemLibrary.h"

AActor* ExampleActor = nullptr;

if (UKismetSystemLibrary::IsValid(ExampleActor))
{
    // Actor is valid
}
else
{
    // Actor is not valid
}

Quit Game

Exits the game application. Can be used to close the game gracefully.

#include "Kismet/GameplayStatics.h"
#include "Kismet/KismetSystemLibrary.h"

APlayerController* PlayerController = UGameplayStatics::GetPlayerController(this, 0); // Get the player controller

UKismetSystemLibrary::QuitGame(
    this,                        // World context object
    PlayerController,            // The player controller initiating the quit (can be null)
    EQuitPreference::Quit,       // EQuitPreference::Quit to exit, EQuitPreference::Background to background
    false                        // Ignore platform restrictions: Set to true to force quit on platforms that might prevent it
);