Search Unity

Question Countdown timer coroutine happening instantly

Discussion in 'Scripting' started by lemmons, Jan 19, 2021.

  1. lemmons

    lemmons

    Joined:
    Jun 20, 2016
    Posts:
    68
    Trying to make my sprites flash using shader graph. That part seems to be working fine, but everything I've seen in tutorials and forums so far says to structure coroutine timers by setting the duration and using Time.deltaTime to either count up or down to it within a `while` loop. However, when I do this...

    Code (CSharp):
    1.    
    2. public tintFadeDuration = 2f;
    3. public tintColor = Color.white;
    4.  
    5. public void FlashUsingShaders()
    6.     {
    7.         StartCoroutine(ShaderFade());
    8.     }
    9.  
    10.     private IEnumerator ShaderFade()
    11.     {
    12.         float tempDuration = tintFadeDuration;
    13.  
    14.         while (tempDuration >= 0f)
    15.         {
    16.             tintColor.a = Mathf.Clamp01(tempDuration / tintFadeDuration);
    17.             material.SetColor("_Tint", tintColor);
    18.             tempDuration -= Time.deltaTime;
    19.             Debug.Log("Color: " + tintColor);
    20.         }
    21.  
    22.         tintColor.a = 0;
    23.         material.SetColor("_Tint", tintColor);
    24.         yield return null;
    25.     }
    ... everything in the `while` loop executes immediately and doesn't wait for the set tintFadeDuration amount even if you put it to something crazy like 300f. The `Debug.Log` is reading correctly and if it would actually wait then I think everything would be fine but I cannot figure out what the deal is.

    Thanks for any guidance in advance!
     
  2. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,911
    Put a
    yield return null;
    at the end of the while loop (between line 19 and 20). That will cause the coroutine to pause for one frame for each iteration of the loop.

    Coroutines don't wait until you explicitly tell them to wait with a yield return statement.
     
    lemmons likes this.
  3. lemmons

    lemmons

    Joined:
    Jun 20, 2016
    Posts:
    68
    Wow, I figured it was something simple I was overlooking—thank you so much!