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

Are co-routines updated every Update/FixedUpdate or neither?

Discussion in 'Scripting' started by yoonitee, Jun 29, 2016.

  1. yoonitee

    yoonitee

    Joined:
    Jun 27, 2013
    Posts:
    2,364
    Say I have a coroutine:

    Code (CSharp):
    1. IEnumerator<int> Fade(){
    2.         Debug.Log ("Fade");
    3.         while(speechBubble.renderer.material.color.a>0){
    4.             Color c=speechBubble.renderer.material.color;
    5.             c.a -= Time.deltaTime;
    6.             speechBubble.renderer.material.color = c;
    7.             yield return 0;
    8.         }
    9.         Debug.Log ("Fade done");
    10.     }
    Will this get updated every frame? Every FixedUpdate? Or none of the above? If so should I use Time.fixedDeltaTime or neither?

    Thanks.
     
    Lightning_A likes this.
  2. SubZeroGaming

    SubZeroGaming

    Joined:
    Mar 4, 2013
    Posts:
    1,008
  3. yoonitee

    yoonitee

    Joined:
    Jun 27, 2013
    Posts:
    2,364
    OK cool. So I can use them just like something in the update function.
     
  4. GarthSmith

    GarthSmith

    Joined:
    Apr 26, 2012
    Posts:
    1,240
    @yoonitee for a coroutine to actually give up control, so Unity can draw a frame, then return to the coroutine, you need to put in yield return null; or yield return new WaitForEndOfFrame(); otherwise the coroutine will just continue until it ends without ever giving Unity a change to draw anything to screen.

    Edit: I guess your
    yield return 0; is doing the same thing? My coroutines usually return type IEnumerator and not IEnumerator<int>.
     
  5. yoonitee

    yoonitee

    Joined:
    Jun 27, 2013
    Posts:
    2,364
    I'm using System.Collections.Generic. It doesn't let me return a null as far as I can see.
     
  6. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,375
    Another handy pattern is that you can define your void Start() function to instead return IEnumerator, and then it is inherently a coroutine.
     
  7. KelsoMRK

    KelsoMRK

    Joined:
    Jul 18, 2010
    Posts:
    5,539
    Coroutines should all be of type System.Collections.IEnumerator

    It used to be the case that yielding anything besides null resulted in a memory allocation but that may have been fixed.
     
  8. Kiwasi

    Kiwasi

    Joined:
    Dec 5, 2013
    Posts:
    16,860
    Yield return null will wait for the next frame. Yeild return new WaitForFixedUpdate() will wait for the next physics update.
     
  9. yoonitee

    yoonitee

    Joined:
    Jun 27, 2013
    Posts:
    2,364
    Thanks. Useful info!! Now I'm ready to overuse co-routines to my hearts content. :)
     
    Kiwasi likes this.