Download

What's the difference between these two ways of creating timers?

Hey,
I am customizing the twinstickshooter c++ project for educational purposes. I am currently in the process of adding a couple of timers to track some input stuff and I discovered 2 ways of creating timers, and was curious as to the difference between the 2.

So here’s my .h


private:

	/* Flag to control firing  */
	uint32 bCanFire : 1;

	/** Handle for efficient management of ShotTimerExpired timer */
	FTimerHandle TimerHandle_ShotTimerExpired;

	// put all sorts of the flapping hold and release timers here
	FTimerHandle TimerHandle_FlapHeld;
	FTimerHandle Timerhandle_FlapReleased;

Here’s the original twinStickPawn.cpp:


UWorld* const World = GetWorld();
			if (World != NULL)
			{
				World->GetTimerManager().SetTimer(TimerHandle_ShotTimerExpired, this, &AtwinStickPawn::ShotTimerExpired, FireRate);
			}

And this is the other way that seems to work that I used (not there’s no validation of world as above):


GetWorldTimerManager().SetTimer(TimerHandle_FlapHeld, this, &AtwinStickPawn::FlapHoldTimerExpired, FlapHoldTimeUntilGlide);

Thanks!

In this case, they are actually exactly the same. The difference between the two versions is that the first approach is a general version that would work for any UObject which has a valid World associated with it. Note that this doesn’t happen automatically. If you just create a UObject, it is not associated with any World object.

The second approach is a convenience function for AActors, which always have a world (the one they are spawned in), so there is no need to check for its existence. Its definition reads


FTimerManager& AActor::GetWorldTimerManager() const
{
	return GetWorld()->GetTimerManager();
}

Ahhh super helpful - thank you!