keywords: [UE4]Timer Related

keywords: UE4 Timer

Register Timer

1st way:

GetWorld()->GetTimerManager().SetTimer(TimerHandle, this, &AMyActor::TestFun, 0.5f, false);

2nd way:

FTimerDelegate TimerDel;
TimerDel.BindUFunction(this, FName("TestFun"));
GetWorld()->GetTimerManager().SetTimer(TimerHandle, TimerDel, 5.f, false);

In 2nd way, TestFun must be marked as UFUNCTION.

3rd way (lambda):

FTimerHandle TimerHandle;
GetWorld()->GetTimerManager().SetTimer(TimerHandle, [=]()
{
    GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Cyan, FString("test+++"));
}, 0.3, false);
Clean Timer
// Ensure the fuze timer is cleared by using the timer handle
GetWorld()->GetTimerManager().ClearTimer(FuzeTimerHandle);

// Alternatively you can clear ALL timers that belong to this (Actor) instance.
GetWorld()->GetTimerManager().ClearAllTimersForObject(this);
How to pass parameters when using GetWorldTimerManager().SetTimer()

Callback Function:

UFUNCTION()
void MyUsefulFunction(int32 x, float y);

.h

FTimerDelegate TimerDel;
 
FTimerHandle TimerHandle;

.cpp

int32 MyInt = 10;
float MyFloat = 20.f;

//Binding the function with specific values
TimerDel.BindUFunction(this, FName("MyUsefulFunction"), MyInt, MyFloat);
//Calling MyUsefulFunction after 5 seconds without looping
GetWorld()->GetTimerManager().SetTimer(TimerHandle, TimerDel, 5.f, false);

Reference:
https://answers.unrealengine.com/questions/165678/using-settimer-on-a-function-with-parameters.html

Profiling: record cost time of function

Quoted from void FTimerManager::Tick(float DeltaTime) in “Engine\Source\Runtime\Engine\Private\TimerManager.cpp”

#if DO_TIMEGUARD && 0
    SCOPED_NAMED_EVENT(FTimerManager_Tick_TIMEGUARD, FColor::Orange);
    TArray<FTimerUnifiedDelegate> RunTimerDelegates;
    FTimerNameDelegate NameFunction = FTimerNameDelegate::CreateLambda([&] {
            FString ActiveDelegates;
            for ( const FTimerUnifiedDelegate& Descriptor : RunTimerDelegates )
            {
                ActiveDelegates += FString::Printf(TEXT("Delegate %s, "), *Descriptor.ToString() );
            }
            return FString::Printf(TEXT("UWorld::Tick - TimerManager, %s"), *ActiveDelegates);
        });


    // no delegate should take longer then 5ms to run 
    SCOPE_TIME_GUARD_DELEGATE_MS(NameFunction, 5);
#endif
Reference

Using C++ Timers in Unreal Engine 4
https://www.tomlooman.com/using-timers-in-ue4/