- Home /
yield return null not working sometimes
Hello all, I have an issue with yield return null in one of my coroutines, which I use for pausing my game. I have a for loop that I want to exit based on a condition, which is Cached_PauseScript.isPaused being true. However, sometimes, even when it is true, the execution will pass over the first yield return null, and go on with the rest of the coroutine. Why is this?
IEnumerator FadeOut()
{
for (float f = 1f; f >= 0f; f -= .02f)
{
if (Cached_PauseScript.isPaused == true)
{
f += .02f;
yield return null;
}
c = rend.material.color;
c.a = f;
rend.material.color = c;
yield return null;
}
Cached_Timeline.Miss();
gameObject.transform.position = new Vector3(0, 0, 0);
rend.material.color = Original;
gameObject.SetActive(false);
}
How do you know that it's not yielding? You could verify it by adding some logging before and after that includes Time.frameCount
.
Answer by Bunny83 · Nov 13, 2019 at 10:11 PM
Uhm, i think you have some misunderstanding here. "yield return null" does not exit the for loop, it just temporarily leave the coroutine and will continue just the next frame at the place where you left it.
To me it's not clear what you actually want to happen. If you want to interrupt the fading while isPaused is true and continue the fading when it's back to false, you just want to do
while (Cached_PauseScript.isPaused )
yield return null;
instead of your if statement. This will wait at this point until isPaused is false and then continue normally
However if you actually want to exit the for loop when isPaused is true, just use break;
instead of your yield. If you want to completely terminate the whole coroutine, use yield break;
Of course when you use just break;
the execution will continue after your for loop with the line
Cached_Timeline.Miss();
If you use yield break;
the coroutine is terminated immediately.