0

How do I break out of this while loop which is inside a coroutine? The debug message appears continuously even after the value is reached.

void Start()
    {
        StartCoroutine(StartFadingIn());

    }
IEnumerator StartFadingIn()
    {
        float i = 0f;
        while(i!=1f)
        {
            Color color = Downward.material.color;
            color.a = i;
            Downward.material.color = color;
            yield return new WaitForSeconds(0.05f);
            i = i+0.1f;
            Debug.Log("Repeat");
        }
    }
  • 2
    Most likely it happens because `i` never gets to **exactly** `1f`, just close enough that if you inspect the variable it *looks* like `1f`. You could instead do `while (Math.Abs(i - 1f) > 1e-5) { ...` to say "close enough is good enough". – Lasse V. Karlsen May 22 '19 at 08:00
  • You might also want to just say `while (i < 1f)`, this should make it simpler to understand, since you're just increasing the variable. – Lasse V. Karlsen May 22 '19 at 08:01
  • Note that the way you've structured your loop means that the last value you *intended* to be set for `color.a` would be `0.9f`. You might just want to make your loop run 11 times instead (once for 0.0f, and then 10 steps to 1.0f). – Lasse V. Karlsen May 22 '19 at 08:02
  • Superb! It works well! Just have to add while '(Mathf.Abs(i - 1f) > 1e-5)' instead –  May 22 '19 at 08:03
  • mathf also contains the neat approximately function `https://docs.unity3d.com/ScriptReference/Mathf.Approximately.html` – yes May 23 '19 at 00:32

1 Answers1

0
void Start()
{
    StartCoroutine(StartFadingIn());

}
IEnumerator StartFadingIn()
{
    float i = 0f;
    while (Mathf.Abs(i - 1f) > 1e-5)
    {
        Color color = Downward.material.color;
        color.a = i;
        Downward.material.color = color;
        yield return new WaitForSeconds(0.05f);
        i = i+0.1f;
        Debug.Log("Repeat");
    }
}