I’m trying to call a function with a delay using GetWorldTimerManager().SetTimer(), but I’m having trouble figuring out the syntax for passing a parameter. This is what I have right now:
After looking around a bit I found that I need to declare a delegate with one parameter and pass that to SetTimer, but I can’t figure out the syntax. Does anyone have a pointer or working example? Thanks!
SetTimer doesn’t take arbitrary delegates. The function signature that matches the call you’re trying to make takes a TimerDelegate and TimerDelegates don’t take parameters.
Here’s an approach that should do what you want. First, create a subclass of APlayerController. For example purposes I’m going to call it AMyPlayerController but you might want to call it something different. Inside of your new player controller class you will need to implement the respawn function. This can just call the function you’ve already got in AMyGameMode if you want.
class AMyPlayerController:: public APlayerController
{
void Respawn();
FTimerHandle RespawnTimerHandle;
}
Now you’ll need to update your RespawnPlayerWithDelay function to call AMyPlayerController::Respawn. It should look something like this:
In this version, the first parameter I gave to SetTimer is a TimerHandle. If you don’t need to use the timer handle later you could also use a temporary one instead of storing it in the player controller. The advantage of keeping it is that you can use it to ask the timer manager how much time is left on the counter and use this for things like displaying a countdown in the UI. The next parameter is a pointer to the object it is going to call the function on. In this case we want it to be on the player controller that is associated with the player we’re going to respawn. The next parameter is the function we’re going to call. Finally we have the delay until we call the function. I hope this clears things up.
Thanks for your answers, both of you. Sorry for not looking back sooner. Camille, your code worked perfectly, thanks! I’m glad I can do this in C++ too now.
For others who find this thread looking to achieve a similar feature, in my final solution I’m also passing an FTimerHandle to ensure that rapid subsequent calls don’t reset the timer causing only one call to get through. Josh Markiewicz said here:
Yeah, it turns out I was just bitten by this myself. Had multiple timers calling the same delegate with different payloads, but only the last one actually fired. Thankfully I remembered your follow-up so it didn’t take much time to figure out what was happening.
Hello guys I have similar problem but a little different, I use this function and it’s working but i can change parameter from another functions it’s a loop timer and i want to change parameter in different states.