It's possible to stop a coroutine from outside the coroutine ?

Like calling GameObject.Destroy(coroutine);

public class Test : MonoBehaviour
{
   private Coroutine coroutine;

    void Update()
    {
        if ( Input.GetKey(KeyCode.A)  coroutine == null )
        {
            coroutine = StartCoroutine(Animate());
        }
        
        if ( Input.GetKey(KeyCode.S)  coroutine != null )
        {
            Destroy(coroutine); // ???
        }
    }
    
    private IEnumerator Animate()
    {
        // Do some animation
    }
}

I saw a CoroutineManager somewhere with all the features I need but I couldn’t find how they do it using the Unity documentation. They probably have a custom implementation of coroutines ??

Thanks in advance.

Use StartCoroutine with a string, then you can use StopCoroutine.

–Eric

Thanks for the answer, but if I use that, for example, when running a coroutine three times, the StopCoroutine will end all three.

I ask this because what is the point of the StartCoroutine returning an instance of the coroutine if you can’t do anything about it ? It’s a nice identifier of the instance of the coroutine and should have a way to stop it using it.

Am I wrong ?

In JavaScript we can use…
InvokeRepeating(“functionX”, 0.1, 0.1);

Then from anywhere we can cancel this function which repeats itself every 0.1 seconds, by using …
CancelInvoke(“functionX”);

That would be a useful feature, and as far as I can tell not one that currently exists.
You can work around it by passing a flag object and checking that in the coroutine, but it’s a bit clumsy.

The same, the flag will stop all my three coroutines at once, and I would LOVE to avoid implementing N coroutines separately and call them separately to achieve this. Also N different instances of the script to achieve multi coroutines also seems a little ugly.

I guess no one ever asked for this before. Not so needed feature.