SetTimer, type for template

Hi…

i using Timer so much from diferent parts of my code… to use timer i write:

FTimerHandle _th;
float _delay = 5.f;
GetWorldTimerManager().SetTimer(_th, this, &AMyClass::MyMethod, _delay, false);

as i write this on each part i want to delay, the code extends too much… so i was wondering in cwriting a template for this:

template <typename T>
void Delay(T* _class, XXXX _method, float _timeDelay){
     FTimerHandle _th;
     GetWorldTimerManager().SetTimer(_th, _class, _method, _timeDelay, false);
}

So as you can see, i cant find the correct type for XXXX place.
this is very similar to std::bind and std::function

You can do this: Paste the following after all #includes, in one line, and no semicolon at the end.

#define Delay(Duration, Looping, FuncName) FTimerHandle Handle; FTimerDelegate Delegate; Delegate.BindUFunction(this, FName(FuncName)); GetWorldTimerManager().SetTimer(Handle, Delegate, Duration, Looping)

Then you can call it like this:
Delay(1.f, false, "MyFuncName");

One drawback is that you need to mark your functions as UFUNCTION(). If someone knows if there’s a way to use delegates with not a UFUNCTION(), I’ll gladly hear it.

2 Likes

Thanks… what is the drawback while using UFUNCTION ?.. i only know compiling time is greater…

Well, the main issue for me is not UFUNCTION itself, but the fact that is has to be a separate function to begin with. If it’s a function used used multiple times, then it’s fine, but if it’s a one-time use, having a separate function also extend the code a lot.
Now I’m using this approach:

FTimerHandle Handle;
FTimerDelegate Delegate;
Delegate.BindLambda([&]()
{
 //Your logic goes here;
});
GetWorldTimerManager().SetTimer(Handle, Delegate, 1.f, false);

It’s several lines of code, but what you want to do after a delay is fully incapsulated within BindLambda, and you don’t have to modify .h and create separate functions.

2 Likes

Using timers frequently is a code smell … what are you trying to achieve by using a lot of timers?

1 Like