jono
jono

Reputation: 35

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;

    }
}

Upvotes: 0

Views: 58

Answers (2)

Saeleas
Saeleas

Reputation: 548

The while condition is why the alpha value does not decrease to 0. ElapsedTime < TotalTime means that in your loop ElapsedTime / TotalTime will never be equal to 1, meaning that the value of alpha will not be 0.

To solve it I would change the condition to check the alpha value of the material:

public IEnumerator colorlerpin7()

{
    float ElapsedTime = 0.0f;
    float TotalTime = 1f;
    Renderer matRenderer =  fluidpef.GetComponent<Renderer>();
    while (matRenderer.material.color.a > 0.0f)

    {
        ElapsedTime += Time.deltaTime;
        matRenderer.material.color = Color.Lerp(new 
        Color(1f, 1f, 1f, 1f), new Color(1f, 1f, 1f, 0f), (ElapsedTime / 
        TotalTime);
        yield return null;

    }
}

Upvotes: 1

Jack10689
Jack10689

Reputation: 181

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);

Upvotes: 1

Related Questions