StopCoroutine must be paired with an argument generated from the StartCoroutine call.
To stop a coroutine, cache the Coroutine object returned by the original StartCoroutine call, and pass it to StopCoroutine.
_exampleCoroutine = StartCoroutine(ExampleCoroutine());
...
StopCoroutine(_exampleCoroutine);// Create a field to cache a reference to our coroutine.
private Coroutine _exampleCoroutine;
void StartExample()
{
// Cache the Coroutine returned from StartCoroutine.
_exampleCoroutine = StartCoroutine(ExampleCoroutine());
}
void StopExample()
{
if (_exampleCoroutine == null)
{
// If there was no coroutine, there is nothing to stop.
return;
}
// Cancel the Coroutine we previously cached.
StopCoroutine(_exampleCoroutine);
// Release the reference for tracking whether the coroutine is running.
_exampleCoroutine = null;
}
IEnumerator ExampleCoroutine()
{
Example logic// Example logic
yield return new WaitForSeconds(1);
Debug.Log("Complete!");
// Release the reference for tracking whether the coroutine is running.
_exampleCoroutine = null;
}
Example helper methods// Because we set _exampleCoroutine to null every time the coroutine ends,
// we can use it to check whether the coroutine is running.
bool IsExampleCoroutineRunning() => _exampleCoroutine != null;StopCoroutine will throw a NullReferenceException if null is passed to it.When a GameObject is deactivated its coroutine will be stopped, but if the script is disabled they will continue.
You may want to stop the coroutine in OnDisable.
// In our example we can just call StopExample.
void OnDisable() => StopExample();Use StopAllCoroutines to halt all running coroutines on a MonoBehaviour.
yield break will exit a coroutine early.
Coroutines will naturally stop when execution reaches the end of the function.