Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Resolved Coroutines & Physics Timesteps (Fixed Update & WaitForFixedUpdate)

Discussion in 'Scripting' started by WonkyDonky, Jun 5, 2023.

  1. WonkyDonky

    WonkyDonky

    Joined:
    Aug 24, 2014
    Posts:
    60
    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?)
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,563
    WonkyDonky likes this.
  3. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,718
    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.
     
    WonkyDonky likes this.
  4. WonkyDonky

    WonkyDonky

    Joined:
    Aug 24, 2014
    Posts:
    60
    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: