Timers Instead of Tick
Beginners put everything in Tick: check the cooldown, count down the respawn, regenerate health, poll whether the door should open. Each of those runs every frame, for every instance, whether or not anything changes. With a few hundred actors, that adds up to a real cost on the game thread, and Tick functions are hard to follow because unrelated logic piles into one function.
Unreal's timer manager runs a function after a delay or at an interval, and costs nothing between firings. Most "every N seconds" and "after N seconds" logic belongs there.
FTimerManager
// ArenaSpawner.h
UCLASS()
class ARENA_API AArenaSpawner : public AActor
{
GENERATED_BODY()
protected:
virtual void BeginPlay() override;
virtual void EndPlay(const EEndPlayReason::Type Reason) override;
UFUNCTION()
void SpawnWave();
UPROPERTY(EditAnywhere, Category = "Spawning", meta = (ClampMin = "0.5"))
float WaveInterval = 20.f;
private:
FTimerHandle WaveTimer;
FTimerHandle WarningTimer;
};
// ArenaSpawner.cpp
#include "TimerManager.h"
void AArenaSpawner::BeginPlay()
{
Super::BeginPlay();
// Call SpawnWave every WaveInterval seconds, first call after 3 seconds.
GetWorldTimerManager().SetTimer(WaveTimer, this, &AArenaSpawner::SpawnWave, WaveInterval, /*bLoop*/ true, /*FirstDelay*/ 3.f);
}
void AArenaSpawner::SpawnWave()
{
// … spawn enemies …
// A one-shot timer with a lambda, bound weakly to this actor:
GetWorldTimerManager().SetTimer(WarningTimer,
FTimerDelegate::CreateWeakLambda(this, [this]() { UE_LOG(LogArena, Log, TEXT("Next wave in 5 s")); }),
WaveInterval - 5.f, false);
}
void AArenaSpawner::EndPlay(const EEndPlayReason::Type Reason)
{
GetWorldTimerManager().ClearAllTimersForObject(this);
Super::EndPlay(Reason);
}| Call | Does |
|---|---|
SetTimer(Handle, Obj, &Class::Fn, Rate, bLoop, FirstDelay) |
start (or restart) a timer; Rate <= 0 clears it |
SetTimer(Handle, FTimerDelegate, Rate, bLoop) |
with a delegate: lambdas, parameters (CreateUObject(this, &X::Fn, Arg)) |
ClearTimer(Handle) |
stop it; the handle becomes invalid |
PauseTimer / UnPauseTimer |
freeze the remaining time |
IsTimerActive(Handle), GetTimerRemaining(Handle) |
query, e.g. for a cooldown UI |
SetTimerForNextTick(…) |
run once on the next frame: break up work or wait for initialization |
Facts worth knowing:
- Timers run on the game thread during the world tick, and they respect time dilation and pause (a paused game pauses timers).
- A looping timer with a rate shorter than the frame time fires several times in one frame to catch up (the manager calls it once per elapsed interval). That is fine for counters and wrong for "spawn one particle per call". Design for it. Newer 5.x releases also accept an
FTimerManagerTimerParametersstruct with abMaxOncePerFrameoption; check that your version has it before relying on it. - Timers bound as
(this, &AMyActor::Fn), withCreateUObjectorCreateWeakLambdahold a weak reference, so they won't call into a dead object.FTimerDelegate::CreateLambdacapturingthishas no such protection. Clearing your handles inEndPlayis cheap insurance either way. - Cooldowns don't need a timer at all: store
ReadyTime = GetWorld()->GetTimeSeconds() + Cooldownand compare when the player presses the button. Zero cost while idle.
A runnable timer manager
The model below implements handles, looping, catch-up firing, clear and pause, and drives them with uneven frame times like a real game's.
#include <iostream>
#include <iomanip>
#include <functional>
#include <map>
#include <string>
class TimerManager {
struct Timer { double Remaining, Rate; bool Loop, Paused = false; std::function<void()> Fn; };
std::map<int, Timer> Timers;
int NextHandle = 1;
public:
double Now = 0;
int SetTimer(std::function<void()> fn, double rate, bool loop, double firstDelay = -1) {
Timers[NextHandle] = {firstDelay >= 0 ? firstDelay : rate, rate, loop, false, std::move(fn)};
return NextHandle++;
}
void ClearTimer(int& h) { Timers.erase(h); h = 0; }
void Pause(int h) { if (Timers.count(h)) Timers[h].Paused = true; }
void Tick(double dt) {
Now += dt;
for (auto it = Timers.begin(); it != Timers.end();) {
Timer& t = it->second;
bool erase = false;
if (!t.Paused) {
t.Remaining -= dt;
while (t.Remaining <= 1e-9) { // catch up: may fire several times
t.Fn();
if (!t.Loop) { erase = true; break; }
t.Remaining += t.Rate;
}
}
it = erase ? Timers.erase(it) : std::next(it);
}
}
};
int main() {
std::cout << std::fixed << std::setprecision(2);
TimerManager tm;
int waves = 0, regenTicks = 0;
int waveTimer = tm.SetTimer([&] { std::cout << "t=" << tm.Now << " wave " << ++waves << "\n"; }, 1.0, true, 0.5);
tm.SetTimer([&] { ++regenTicks; }, 0.1, true);
tm.SetTimer([&] { std::cout << "t=" << tm.Now << " intro text hidden\n"; }, 0.8, false);
double frames[] = {0.25, 0.25, 0.4, 0.1, 0.5, 0.3, 0.6}; // a hitch at 0.6 s
for (double dt : frames) {
int before = regenTicks;
tm.Tick(dt);
std::cout << "frame dt=" << dt << ": regen fired " << regenTicks - before << "x\n";
if (waves == 2 && waveTimer) {
tm.ClearTimer(waveTimer);
std::cout << "wave timer cleared after wave 2\n";
}
}
}frame dt=0.25: regen fired 2x
t=0.50 wave 1
frame dt=0.25: regen fired 3x
t=0.90 intro text hidden
frame dt=0.40: regen fired 4x
frame dt=0.10: regen fired 1x
t=1.50 wave 2
frame dt=0.50: regen fired 5x
wave timer cleared after wave 2
frame dt=0.30: regen fired 3x
frame dt=0.60: regen fired 6x
The regen timer fired between 1 and 6 times per frame depending on the frame time, which is exactly what "catch up" means. If each call had spawned a particle, the 0.6 s hitch would have spawned a burst. Note also that the 0.8 s intro timer fired at t = 0.90: timers are checked once per frame, so they fire at the end of the frame in which they came due.
When Tick is right
Tick is the right tool for things that really change every frame: smoothing a camera, interpolating a UI bar, steering a projectile with custom physics, reading input-driven aim. Even then, set PrimaryActorTick.TickInterval if 10–30 Hz is enough, and turn tick off when idle with SetActorTickEnabled(false).
Test yourself
A looping timer has Rate = 0.1 s and the frame took 0.35 s. How many times does it fire that frame?
- 0
- 1
- 3
- It depends on the tick group
What is the cheapest way to implement a 2-second ability cooldown?
- Decrease a float in Tick
- Store the time when it becomes ready and compare on use
- A looping 0.01 s timer
- A Behavior Tree
Where should an actor clear its timers?
- In the constructor
- In EndPlay (e.g. ClearAllTimersForObject)
- In Tick
- Timers can't be cleared