I’m searching the way to call a function that have some arguments by SetTImer function in C++ but I couldn’t.
I need to satisfy below conditions
- Loop function with interval and duration
- Send arguments to function when loop start
Thank you
I’m searching the way to call a function that have some arguments by SetTImer function in C++ but I couldn’t.
I need to satisfy below conditions
Thank you
Short answer: you can’t. You can only pass the parameters that are already defined in the timer delegate. And there are none.
However, you don’t receive any arguments from the timer itself, you’re getting them elsewhere. Nothing stops you from having 2 functions, one for the timer tick, and the other they will be called in the first one, with all the parameters you might need.
Some things are possible with help of lambda captures:
int value1 = 123;
GetWorld()->GetTimerManager().SetTimer(_, [value1]() {
//do things with value1 here
}, Timeout, false);
Also, depending on your setup instead of “send arguments” you probably may use “function look for arguments themself in known place”
I fixed the code to
float Amount = 123;
GetWorldTimerManager().SetTimer(TimerHandle, [&, Amount] {
this->Foo(Amount);
}, Interval, true);
I found that I can’t use value outside of lambda without specifying [value_you_like]. Witch cause readind unexpected memory.
In addition, [&] also needed to call non static function inside lambda.
If this is wrong, please correct me. Thank you for your answers.
In case you need “this”, iirc you have to capture it explicitely(though i may be wrong). Anyway, i think this way it should work:
float Amount = 123;
TWeakObjectPtr<CURRENT_OBJECTs_CLASS> WeakThis(this);
GetWorldTimerManager().SetTimer(TimerHandle, [WeakThis, Amount] {
if(!WeakThis.IsValid())
{
//this died before callback triggered
return;
}
this->Foo(Amount);
}, Interval, true);
upd: replaced raw this
pointer in example with weak pointer
. This is required since this
object can die before callback will be called, and it can die due to quite a variety of reasons. weak pointer
let you safely track this. For further info read the official documentation about weak pointers
.
also, i hope it should be obvious that CURRENT_OBJECTs_CLASS
is not some global macro and have to be replaced with your actual current class name, like AActor
or AMyGameMode
This looks better tha mine