How can I setup custom ticks?

fai domanda su tick cusomizzato (every 2 frames, every n (exposed parameter) updates of the physics engine, 10 times a second)

Hello! Good day everyone!
So basically we all know about the event tick, which is called every frame, and I don’t know you guys but that’s the only “tick” event I know, so here’s my question:
Is there a way to implement “custom tick” functions? To speak my mind, I’ll make some examples:

  • A function that is called every 4 updates of the physics engine (not framerate-dependant)

  • A function that is reliably called 10 times a second

I am pretty sure this is a common thing in programming but I looked around google and the wiki and there’s no documentation for it in UE4!

Use SetTimer on the world timer manager.

Its signature/declaration is:

template< class UserClass >
FORCEINLINE void SetTimer(FTimerHandle& InOutHandle, UserClass* InObj, typename FTimerDelegate::TUObjectMethodDelegate< UserClass >::FMethodPtr InTimerMethod, float InRate, bool InbLoop = false, float InFirstDelay = -1.f)
{
	InternalSetTimer(InOutHandle, FTimerUnifiedDelegate( FTimerDelegate::CreateUObject(InObj, InTimerMethod) ), InRate, InbLoop, InFirstDelay);
}

Use it like this:

Somewhere in .h:

FTimerHandle TimerHandle;

UFUNCTION()
void ReceiveUpdateTimer();

Somewhere in .cpp, possibly in BeginPlay() or something like that (but not the class constructor!):

	...
	GetWorld()->GetTimerManager().SetTimer(TimerHandle, this, &UMyObjectClass::ReceiveUpdateTimer, 5.0f /* every 5 seconds */, true /* keep calling over and over */, 0.2f /* wait 0.2 seconds before calling it the first time */);
	...

And to stop the callback, do something like this

	// Make sure to check if world is valid, because you might end up stopping your timer during a Destroy(), and the world may be invalid at this point.
	if (GetWorld())
	{
		GetWorld()->GetTimerManager().ClearTimer(TimerHandle);
		TimerHandle.Invalidate();
	}

This is so helpful! Thanks a bunch!

No problem :slight_smile: Mark as answer so others can find it, if you want (though the AnswerHub will unmark it if you leave another comment, which is kind of annoying)