How to use Delays in C++ in Unreal Engine

Jul, 2 2021— #basic

Some developers are wondering about the C++ equivalent of the "Delay" node in Blueprints.

In C++, it is not recommended to make delays for cosmetic things, but if there are some things that require high optimization, then consider the following methods below, which are related to the FTimerHandle object.

To begin with, there are two ways to analogue Delay, which can be implemented inside one method (without declaring another). They practically do not differ from each other. Use the option that is more readable and convenient.

1. Using FTimerDelegate with BindLambda

FTimerDelegate TimerDelegate;
TimerDelegate.BindLambda([&]
{
	UE_LOG(LogTemp, Warning, TEXT("This text will appear in the console 3 seconds after execution"))
});

FTimerHandle TimerHandle;
GetWorld()->GetTimerManager().SetTimer(TimerHandle, TimerDelegate, 3, false);

2. Using FTimerHandle only

FTimerHandle TimerHandle;
GetWorld()->GetTimerManager().SetTimer(TimerHandle, [&]()
{
	UE_LOG(LogTemp, Warning, TEXT("This text will appear in the console 3 seconds after execution"))
}, 3, false);

 

The second way is to use a delay to execute another function. The example below uses dynamic binding, but you can also bind via BindUFunction.

1. If there are no input parameters

FTimerHandle TimerHandle;
GetWorld()->GetTimerManager().SetTimer(TimerHandle, this, &UObject::MethodWithDelay, 3, false);

2. If there are input parameters

int32 ParameterToPass = 100; // You can use any supported variable type

FTimerHandle TimerHandle;
FTimerDelegate TimerDelegate = FTimerDelegate::CreateUObject(this, &UObject::MethodWithDelay, ParameterToPass);
GetWorld()->GetTimerManager().SetTimer(TimerHandle, TimerDelegate, 3, false);
By Georgy Treshchev

Unreal Engine Developer. Contact for any questions. Telegram chat, e-mail, Github.