Search code examples
c#unity-game-enginecoroutinelerp

Coroutine does no play all the way through


Unfortunately my co routine does not play all the way through. It is supposed to fade an object so it's alpha is 0. However it fades to .039.

{
    StartCoroutine(colorlerpin7());
    yield return null;
}

public IEnumerator colorlerpin7()

{
    float ElapsedTime = 0.0f;
    float TotalTime = 1f;
    while (ElapsedTime < TotalTime)

    {
        //  fades out atipical
        ElapsedTime += Time.deltaTime;
        fluidpef.GetComponent<Renderer>().material.color = Color.Lerp(new 
        Color(1f, 1f, 1f, 1f), new Color(1f, 1f, 1f, 0f), (ElapsedTime / 
        TotalTime));
        yield return null;

    }
}

Solution

  • this looks like the "correct" behaviour since your ElapsedTime will be bigger then TotalTime before you will get to an alpha of 0 (or a lerp value of 1) e.g.

    ->frame x ElapsedTime is 0.97 your lerp value is 0.97.

    ->frame x+1 ElapsedTime might be already 1.1, so you will jump out of the loop.

    Just add this code after the loop:

    fluidpef.GetComponent<Renderer>().material.color = Color.Lerp(new 
        Color(1f, 1f, 1f, 1f), new Color(1f, 1f, 1f, 0f), 1);