Timers in UObjects

Hey, I’m trying to use a timer in a UObject’s function but the code examples that I’m finding all involve Actors. Here’s what I’m trying:

FTimerHandle FadeTimerHandle;
GetWorld()->GetTimerManager().SetTimer(FadeTimerHandle, this, &UGameManager::SwitchScreen, 0.5f);

I also tried another version:

.SetTimer(FadeTimerHandle, &UGameManager::SwitchScreen, 0.5f, true);

The first one compiles but gives me an access violation on run, the second gave me a template error. How would I go about doing this properly?

We can find an example of using a UObject in several areas of the source code. My example comes from AbilityTask_Repeat.cpp in the Gameplay Abilities modules. Here we have a time set on the ability task.

GetWorld()->GetTimerManager().SetTimer(TimerHandle_PerformAction, this, &UAbilityTask_Repeat::PerformAction, TimeBetweenActions, true);

TimeBetweenActions is a float member variable.
TimerHandle_PerformAction is an FTimerHandle structure.

What you are missing is the ‘this’ parameter in your second code example.

So your code should be:

.SetTimer(FadeTimerHandle, this, &UGameManager::SwitchScreen, 0.5f, true);

Also, if you are getting access violations during runtime, your objects may be going out of scope or you may have invalid pointers. GetWorld() returns a pointer, so make sure that the GetWorld() return’s a valid pointer by checking against nullptr. Also make sure that you are not destroying the object (UGameManager) after setting the timer and make sure it is not destroyed before the timer callback is called.

Yep, when you derive from UObject, GetWorld returns nullptr by default. So you need to override it and find the world. Often, you know your object will have an actor/component as its outer and can do:

return GetOuter()->GetWorld();

On the other hand, if this object has no inherent attachment to a world, you can get the timer manager from the UGameInstance instead.

The override and GetOuter()->GetWorld() did the trick, thank you!

A side question, what’s the best way to search for code examples? Download the repo and git pickaxe search?

To anyone in the future: if your outer is a level, it’ll return a non-null world but it won’t work for setting timers. They exist and you can use their handle to see that they’re active and non-paused, but their time remaining never changes.

I ended up just using my UI to get the world (Which works since UUserWidgets have a working GetWorld).