Coroutines & Physics Timesteps (Fixed Update & WaitForFixedUpdate)

FixedUpdate() runs at fixed rate (50fps), so when game is eg. 25fps, its called twice

but would yield return new WaitForFixedUpdate()
in a coroutine make the coroutine run twice if game is 25 fps?

or just regurlarly once eg. right after FixedUpdate has been called twice?

This is bit unclear

Thank you

(If it only updates once is there way to make the coroutine work like FixedUpdate so it works with physics?)

Timing is a very abstract thing to grasp.

It is often useful to think in terms of engineering a solution for whatever odd timing situation you are doing.

Here is some timing diagram help:

https://docs.unity3d.com/Manual/ExecutionOrder.html

Here is an abbreviated and better-annotated version of the above:

https://discussions.unity.com/t/904929

1 Like

The coroutine will only run as many times as you tell it to run with StartCoroutine.

WaitForFixedUpdate will make it wait to resume until after the next physics simulation frame. If you do a loop with WaitForFixedUpdate in it, that will essentially make that code inside the loop run at a cadence with FixedUpdate (50 times per second by default.

2 Likes

Thank you for the answers!

I did a quick test to make sure by adding counters to FixedUpdate and the Coroutine and lowering the fps with Application.targetFramerate and yes, using yield return new WaitForFixedUpdate() in while loop inside coroutine makes the coroutine run multiple times per frame if fps is low enough, as many times as the fixed update

Iā€™m doing custom animations with the coroutines and the purpose was to essentially do this functionality from the animator:

So if I want to run physics inside a coroutine, using WaitForFixedUpdate is the best way to do so, right?