Some developers are wondering about the C++ equivalent of the Delay
node in Blueprints.
There are two ways to implement Delay
that are very similar. Use the option that is more readable and convenient for you.
Lambas
Using FTimerDelegate
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);
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);
Separate functions
The second way is to use a delay to execute another function.
Without input parameters
FTimerHandle TimerHandle;
GetWorld()->GetTimerManager().SetTimer(TimerHandle, this, &UObject::MethodWithDelay, 3, false);
With 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);