0
0
Unityframework~5 mins

Stopping coroutines in Unity

Choose your learning style9 modes available
Introduction

Stopping coroutines lets you pause or end tasks that run over time in your game. This helps control game actions and save resources.

When you want to stop a repeating animation or effect early.
If a player cancels an action that was running over time.
To end a timed event when the game state changes.
When cleaning up coroutines before switching scenes.
To prevent multiple coroutines from running the same task.
Syntax
Unity
StopCoroutine(coroutineReference);
StopCoroutine("CoroutineName");
StopAllCoroutines();

You can stop a coroutine by its reference or by its name as a string.

StopAllCoroutines() stops every coroutine running on that script.

Examples
Stop a coroutine using its stored reference.
Unity
Coroutine myCoroutine = StartCoroutine(MyCoroutine());
StopCoroutine(myCoroutine);
Stop a coroutine by its name as a string.
Unity
StartCoroutine("MyCoroutine");
StopCoroutine("MyCoroutine");
Stop all coroutines running on this script.
Unity
StartCoroutine(MyCoroutine());
StopAllCoroutines();
Sample Program

This program starts a coroutine that prints numbers every second. After 3 seconds, it stops the coroutine and prints a message.

Unity
using UnityEngine;
using System.Collections;

public class CoroutineStopExample : MonoBehaviour
{
    private Coroutine runningCoroutine;

    void Start()
    {
        runningCoroutine = StartCoroutine(PrintNumbers());
        Invoke("StopPrinting", 3f); // Stop after 3 seconds
    }

    IEnumerator PrintNumbers()
    {
        int count = 1;
        while (true)
        {
            Debug.Log(count);
            count++;
            yield return new WaitForSeconds(1f);
        }
    }

    void StopPrinting()
    {
        StopCoroutine(runningCoroutine);
        Debug.Log("Coroutine stopped.");
    }
}
OutputSuccess
Important Notes

Stopping a coroutine only affects that coroutine instance, not others started from the same method.

If you stop a coroutine by name, make sure the name matches exactly.

StopAllCoroutines() is useful but stops everything, so use it carefully.

Summary

Stopping coroutines helps control ongoing tasks in Unity.

You can stop coroutines by reference, by name, or all at once.

Use stopping to manage game flow and save resources.