Search Unity

  1. Good news ✨ We have more Unite Now videos available for you to watch on-demand! Come check them out and ask our experts any questions!
    Dismiss Notice

How to: Yield a Frame?

Discussion in 'Scripting' started by YetAnotherKen, Sep 9, 2019.

  1. YetAnotherKen

    YetAnotherKen

    Joined:
    Jun 17, 2019
    Posts:
    30
    I have seen several references to yielding a frame. Can anyone tell me how to do this?
     
  2. Ian094

    Ian094

    Joined:
    Jun 20, 2013
    Posts:
    1,525
    Code (CSharp):
    1. yield return new WaitForEndOfFrame();
     
    YetAnotherKen likes this.
  3. YetAnotherKen

    YetAnotherKen

    Joined:
    Jun 17, 2019
    Posts:
    30
    Thank you!
     
  4. Antistone

    Antistone

    Joined:
    Feb 22, 2014
    Posts:
    2,201
    That's not quite correct. The best way to make a coroutine wait for one frame is usually

    yield return null;


    WaitForEndOfFrame waits until a specific (unusual) point within the generation of a specific frame; it's used if you need to control the order that stuff happens within a single frame. If you're doing it over and over in a loop, it will give a similar end result, but the first time you do it you won't actually be waiting a frame (just until the end of the current frame), and it will cause your coroutine to run during a weird part of the game loop.

    This diagram shows the relative timing:
    https://docs.unity3d.com/Manual/ExecutionOrder.html
     
  5. DonLoquacious

    DonLoquacious

    Joined:
    Feb 24, 2013
    Posts:
    1,667
    Worth noting I think in the interest of being pedantic (and possibly stopping another discussion on this that may occur down the road before it starts) that you'll see both "yield return null;" and "yield return 0;" used from time to time, but that, as Antistone suggests, it's the null method that you should use. They're functionally identical in that they both wait a single frame, but null doesn't allocate an integer or box/unbox its value under the hood to determine that it should just throw it away anyways. While this is a relatively tiny optimization on its own, it compounds quickly in some situations, and it's an easy one to get into the habit of making, right up there with caching YieldInstructions when you have no specific reason not to.

    Cheers. =)
     
  6. Jorhoto

    Jorhoto

    Joined:
    May 7, 2019
    Posts:
    69
    Good point, I liked your post.
     
unityunity