StopCoroutine
- Game Development course
- Intermediate
- Lesson 47/83
- 4 min
Learn to stop a running coroutine with StopCoroutine.
Halting with StopCoroutine
To terminate a running coroutine before it naturally finishes, the StopCoroutine() method is called. Passing the Coroutine reference cached during launch is the most robust approach.
// Cancelling active routine via reference
if (activeRoutine != null) {
StopCoroutine(activeRoutine);
}For example, taking damage can interrupt an in-progress spell-casting coroutine immediately.
StopAllCoroutines and GameObject deactivation
To reset all scheduled routines on an object simultaneously, StopAllCoroutines() is called. Furthermore, deactivating a GameObject via SetActive(false) automatically halts all its active coroutines.
void OnDisable() {
// Clean up coroutines when object is disabled
StopAllCoroutines();
}However, merely setting enabled = false on the component does not stop coroutines; the GameObject itself must be deactivated.
Practice Print stop command and status
Assign "StopCoroutine" to command and "Cancelled" to status. Print Command: StopCoroutine | Status: Cancelled to the console.
Starter code
using System;
class Program
{
static void Main()
{
// command ve status değerlerini tanımlayıp yazdır
}
}Sample solution
using System;
class Program
{
static void Main()
{
string command = "StopCoroutine";
string status = "Cancelled";
Console.WriteLine("Command: " + command + " | Status: " + status);
}
}Expected output
Command: StopCoroutine | Status: Cancelled
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which method is called to halt ALL actively running coroutines on a MonoBehaviour in one command?
- ClearRoutines();
- AbortAll();
- StopAllCoroutines(); Correct answer
- KillCoroutines();
Explanation: StopAllCoroutines() cancels all coroutine routines actively running on the respective script in one call.
2 Stop running coroutine via reference
StopCoroutine(____);
StopCoroutine(activeRoutine);
Explanation: To halt a specific coroutine, the reference returned by StartCoroutine is passed as a parameter.
3 Stopping and cleanup concepts
| Term | Meaning |
|---|---|
StopCoroutine |
Stop specific coroutine early |
StopAllCoroutines |
Cancel all running coroutines |
SetActive(false) |
Deactivate & stop coroutines |
Cleanup |
Clean tasks on deactivation |