简体   繁体   中英

End Coroutine if one of two conditions becomes true

I'm not fully understanding coroutines.

If I have a coroutine that does something each frame, how do I end this looping behaviour if either of two conditions become true?

And when I say end, I also mean destroy, not put into a holding state or other paused or non completed state, so I can then restart the coroutine if a different condition becomes true.

If the conditions exist outside of the coroutine, you use StopCoroutine :

var coroutine = StartCoroutine(MyRoutine());
...
if (conditionA || conditionB) {
    StopCoroutine(coroutine);
}

If the conditions exist inside of the coroutine, you just yield break :

IEnumerator MyRoutine() {
    while (true) {
        if (conditionA || conditionB) {
            yield break; // stop stepping this
        }
        yield return null; // continue stepping next frame
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM