Confused about StopAllCoroutines() C#

I have a spawner script that will yield return new WaitforSeconds a certain amount of time, then spit out an enemy.

public IEnumerator StartEnemyWave (int numberOfEnemies, float interval)
	{
        float temp = interval / uIController.levelProgressTotal;
        uIController.actualProgressBarTotal += temp;
        //spawns a certain amount of enemies inbetween a variable interval
        for (int i = 0; i < numberOfEnemies; i++)
		{
            if (!levelController.gameOver)
            {
                int enemyIndex = levelController.currentSpawnData.enemySelection [levelController.currentWave].enemiesThisWave *;*

SpitOutEnemy (enemyIndex);
print ("spawning : " + levelController.currentSpawnData.enemySelection [levelController.currentWave].enemiesThisWave.Length);
print ("every " + levelController.currentSpawnData.timeBetweenEnemies [levelController.currentWave]);
yield return new WaitForSeconds (interval);
}
else
{
print (“stopping the spawner”);
yield return null;
}

  • }*
    My problem is in that I can’t seem to shut this coroutine down when I want to.
    I tried making a cheat button which ends the level and brings you back to the level select screen. In that button press it has the function “StopAllCoroutines()”. But when I select a new level, sure enough the spawner is still firing off enemies having never been shut down.
    What am I missing here? What would cause StopAllCoroutines to not find this and shut it down, even during a yield return new WaitForSeconds(); ?

StopAllCoroutines() will shut down the coroutines run by the particular monobehavior its called upon. Can’t see in your code the portion that stops the coroutine, but I’m guessing that you are assuming ‘StopAllCoroutines()’ will stop all coroutines across the entire game. It doesn’t work that way.

Make a method “X” in your Spawner class that calls StopAllCoroutines() and call X from anywhere else, via reference to your Spawner class.

I have experienced similar problem with coroutines. I guess if coroutine ha s a loop running in it, then StopAllCoroutines() doesn’t work.
My suggestion is to use break; statement for the termination of the loop and then you can use StopAllCoroutines() function for that take a boolean and use it in your loop. like

for(int i = 0; i < numberOfEnimies;  i++){

        if(isStopCoroutine)
                break;
}

It will do your work (Hopefully).

maybe you can try

 youscript.gameObject:SetActive(false);