Often you design coroutines to naturally end when certain goals are met.
IEnumerator TickFiveSeconds()
{
var wait = new WaitForSeconds(1f);
int counter = 1;
while(counter < 5)
{
Debug.Log("Tick");
counter++;
yield return wait;
}
Debug.Log("I am done ticking");
}
To stop a coroutine from "inside" the coroutine, you cannot simply "return" as you would to leave early from an ordinary function. Instead, you use yield break
.
IEnumerator ShowExplosions()
{
... show basic explosions
if(player.xp < 100) yield break;
... show fancy explosions
}
You can also force all coroutines launched by the script to halt before finishing.
void OnDisable()
{
// Stops all running coroutines
StopAllCoroutines();
}
The method to stop a specific coroutine from the caller varies depending on how you started it.
If you started a coroutine by string name:
StartCoroutine("YourAnimation");
then you can stop it by calling StopCoroutine with the same string name:
StopCoroutine("YourAnimation");
Alternatively, you can keep a reference to either the IEnumerator
returned by the coroutine method, or the Coroutine
object returned by StartCoroutine
, and call StopCoroutine
on either of those:
public class SomeComponent : MonoBehaviour
{
Coroutine routine;
void Start () {
routine = StartCoroutine(YourAnimation());
}
void Update () {
// later, in response to some input...
StopCoroutine(routine);
}
IEnumerator YourAnimation () { /* ... */ }
}