0

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;

    }
}
jono
  • 35
  • 8

2 Answers2

1

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);
Jack10689
  • 181
  • 4
1

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;

    }
}

Saeleas
  • 538
  • 2
  • 8
  • `Color.Lerp` will do clamp for you. – shingo Apr 23 '19 at 12:50
  • `Color.Lerp` clamps the third paramenter, not the color value, so your code will get the same result as the OP's. I think his problem is not about the clamp. – shingo Apr 23 '19 at 12:57
  • I updated my answer, sorry for the trouble. The problem, as already noted, is in the `while` that ends a frame too early. In this answer I change the condition to check on the alpha value instead of the `ElapsedTime` – Saeleas Apr 23 '19 at 13:01