Same coroutine on multiple Gameobjects

Hi all,

I have recently started learning unity and I am currently trying to set up three different enemy spawners - top(TopSpawner Preab), leftside(SideSpawner Prefab), rightside(SideSpawner Prefab). They all spawn enemies and it works fine, but when I want to transition into a bossfight, I was looking to set the “normalGameMode” to false via a bool function within this script (enemySpawner) which being called in another one called Gamecontrol.

This is what my coroutine looks like:

 private IEnumerator SpawnEnemy()
        {
            while(normalGameMode)
            { 
                TopSpawnerRangeSetup();
                SideSpawnerRangeSetup();
                InstantiateEnemy();
                var spawnDelayIndex = Random.Range(spawnDelayMin, spawnDelayMax);
                yield return new WaitForSeconds(spawnDelayIndex);
            }
        }

this is the function I change the variable with:

public bool SetBossMode()
    {
        return normalGameMode = false;
    }

Whenever I change the normalGameMode to false, only the first spawner stops, all others continue to spawn enmies. Why does it only stop one?

I would really appreciate your help,

Thanks,

JackyAce

Try this :

    private IEnumerator SpawnEnemy()
             {
                 while(normalGameMode)
                 { 
                     TopSpawnerRangeSetup();
                     SideSpawnerRangeSetup();
                     InstantiateEnemy();
                     var spawnDelayIndex = Random.Range(spawnDelayMin, spawnDelayMax);
                     yield return new WaitForSeconds(spawnDelayIndex);
                 }
             }
Stop it when its bossFight
public void SetBossMode()
     {
         normalGameMode = false;
     }

Well, where and how is your “normalGameMode” variable declared? If it’s an instance member variable of the class then each spawner has its own variable. You could make the variable static, though too many static variables can quickly become a mess. Another option would be to have a list of all your spawners in one of your game manager classes and have them turned off that way.

Note that currently your coroutine will be stopped completely. We don’t know how you started your coroutine but if you want to resume the normal spawning business you would need to restart the coroutine. Sometimes it’s easier to just wait in the coroutine during the boss fight. So instead of

while(normalGameMode)
{
    // [...]

you could simply do:

while(true)
{
    while (!normalGameMode)
        yield return null;
    // [...]

In this case while the boolean is false the coroutine will wait in the inner while loop until the boolean is true again at which point it will resume the normal spawning.

Of course this doesn’t change your original issue how you signal all your spawners at once. In your case making the variable static should be enough.