We are bouncing back to C++ Fundamentals this time looking at FTimerHandle and Timers in general by messing around with our props.
Additionally you can always find the sample project on
our GitHub page.
Timers ?! What are they ?
Timers allow us to trigger events based on elapsed time in the form of creating asynchronous callbacks to specific function pointers.
Plain English: we light a fuse, let it burn down, something explodes !
How do we make these magical exploding clocks ?
Well let’s take a look at some code as these things are pretty easy to understand.
GetWorld()->GetTimerManager().SetTimer(TriggerDestroyTimerHandle, this, &ADestructibleProp::TriggerDestroy, 5.f, true);
// do stuff
So as you can see the implementation is pretty easy to understand.
We are creating a timer from our Time Manager object.
We are then registering this call back to use our Timer Handle.
Then we assign a callback method to be triggered at the end of our countdown.
Then finally we set that the countdown duration is 5 seconds.
Excellent ! Let’s blow some things up.
Timers can also be used to trigger modifications to specific values every so often. In this case we are going to simulate a fuse that will count down every second before it triggers an event.
First we are going to call the timer as we did previously, except this time we are going to call a new method and have this timer run every second.
GetWorld()->GetTimerManager().SetTimer(TriggerDestroyTimerHandle, this, &ADestructibleProp::TriggerCountdownToDestroy, 1.f, true);
Then we add in our count down logic
Finally we add in our implementation where we modify our count down variable by subtracting one from it every second.
Additionally we trigger a second timer call to our original method by randomly generating a delay before it gets triggered.
// count down to zero
if (--TriggerCountdown <= 0)
int32 RandomDelay = FMath::RandRange(1, 5);
GEngine->AddOnScreenDebugMessage(-1, 3.f, FColor::Orange, "Boom ! with a delay of: " + FString::FromInt(RandomDelay));
GetWorld()->GetTimerManager().SetTimer(TriggerDestroyTimerHandle, this, &ADestructibleProp::TriggerDestroy, RandomDelay, true);
GEngine->AddOnScreenDebugMessage(-1, 3.f, FColor::Orange, "Counting down to explosion: " + FString::FromInt(TriggerCountdown));
This allows us to have custom implementations in our timers that perform very specific work.
Pretty cool !
Below you can find a few more links with some additional reading material: