How can I use a delay or a sleep in C++?

How can I use a delay in C++ like you can do in blueprints with the delay node?

1 Like

You can make your own functions to do so, all you need is to supply them with the DeltaSeconds that you get from any tick function.

Tried it but the game freezes each time. I guess it just loops so fast that it reaches the infinite loop threshold.

void ASGameMode::TimerFunction(float seconds) {
	float startTime = ()->TimeSeconds;
	float endTime = startTime + seconds;

	while (endTime > startTime)
	{
		startTime = ()->TimeSeconds;
	}
}

I also had a version using DeltaTime and while it ran ok, it didn’t have any visible effect.

Why don’t you use timers ?

GetWorldTimerManager().SetTimer(...)

Best regards

Pierdek

FPlatformProcess::Sleep(time);

It can will stop code execution which means it game will freeze if it will be executed in main thread

You need to use timers are they are 100% multithreaded, you can make them execute in loop, there also function to pause timers and check there time status, so try to operate it somehow. If you want time start diffrent for each actor, set the timers from different class (in first argument of SetTimer() is object you want function to be executed in)

Think out of the box, thats what you need to do in this kind of situations ;]

Timer did work, thanks. I set it per object as you suggested and then to keep them from all going at once I just made a timer variable and incremented it in the loop.

GetWorldTimerManager().SetTimer(Deck[i], &ASCard::SetDealing, theTime, false);
theTime += 0.1f;

Timer works. I just needed to set it for all the objects instead of the GameMode class I was calling it in. Thanks.

This was your problem:

while (endTime > startTime)
{
   startTime = ()->TimeSeconds;
}

This loop completely locks up a whole CPU core/thread until startTime = endTime. That thread can do nothing except call ()->TimeSeconds; In fact, it might even be blocking Unreal Engine from updating TimeSeconds until the loop ends (which it won’t if TimeSeconds doesn’t change because it’s waiting for the loop to end so it gets its turn on the CPU – infinite loop).

What you really want is to check to see if ()->TimeSeconds >= endTime but, if it’s not, sleep your code for a bit and check later.

That’s where timers come in. No loops, just execute once, let other code run, execute your function once more, let more code run, etc.