How do I stop coroutine?

I have a coroutine that creates spheres. I want the coroutine to stop after creating 200 spheres. I have a counter in another class that counts the number of spheres created. I have tried using StopCoroutine(), but no luck. Any ideas??

Please note, that StopCoroutine method will only stop coroutines called with StartCoroutine overload, that accepts coroutine name as string. If you have coroutine:

IEnumerator MyCoroutine()
{
    // content
}

and you call it using

StartCoroutine(MyCoroutine());

then you won’t be able to stop it using

StopCoroutine("MyCoroutine");

For the StopCoroutine method to work, you have to start it using

StartCoroutine("MyCoroutine")

Apart from above, you can stop a coroutine in a different way. For example you can use

IEnumerator MyCoroutine()
{
    for(var i = 0; i < 200; i++)
    {
        // instantiate your sphere
        yield return null;
    }
}

After exiting for loop, coroutine will stop. You can also use yield break to stop execution of coroutin, if specific condition is met:

IEnumerator MyCoroutine()
{
    while(true)
    {
        // instantiate your sphere

        if(/*some condition check*/)
        {
            yield break;
        }
        else
        {
            yield return null;
        }
    }
}

At some point, StopCoroutine(Coroutine c); was added to the MonoBehavior interface. So it appears you can also do:

 Coroutine theCoroutine = StartCoroutine(MyCoroutine());

and later:

StopCoroutine(theCoroutine);