How to end a looping function?

I have a looping function that spawns waves of enemies, but I cant figure out a way to stop the loop. I want it to end after a definable wave of enemies have spawned. Here is the script im using:

void Start()

  {
  
  StartCoroutine (SpawnWaves());
   
  }

IEnumerator SpawnWaves ()

  {
  yield return new WaitForSeconds (startWait);
  while (true)
  {
  for (int i = 0; i < hazardCount; i++)
  {
  GameObject hazard = hazards [Random.Range (0,hazards.Length)];
  Vector3 spawnPosition = new Vector3(spawnValues.x, Random.Range(-spawnValues.y, spawnValues.y), spawnValues.z);
  Quaternion spawnRotation = Quaternion.identity;
  Instantiate(hazard, spawnPosition, spawnRotation);
  yield return new WaitForSeconds(spawnWait);

  }
  yield return new WaitForSeconds(waveWait);

Please indent your script properly. Tab can’t be used but spacebar sure can be, 4 spaces mimics a tab.

1 Like

You can use the break keyword (https://msdn.microsoft.com/en-us/library/adbctzc4.aspx) to end a loop. Just keep in mind it will stop the loop it is within first. So if you put it within that for loop it will stop the for loop rather than the while loop.

That said I recommend you don’t create loops in a way that easily allows them to be infinite. You can very quickly lock up your game, the editor, and possibly even the OS it’s running on. A far better idea is to create a boolean and check if it’s set to true within the loop. Like this.

bool spawnCondition = false;
while (spawnCondition == false)

Then when you’ve decided that the condition has been met you simply set it to true and the loop will end.

2 Likes

You could also use a for loop. There is no reason for a while loop here.

2 Likes

Sometimes easier is better; I always use bool for recurring functions even though break might be more “correct”. I didn’t even know about loops until I accidentally made an infinite loop script, crashed Unity with my script (every time I tried to play, obviously) and reported it as a bug. Was pretty embarrassing for me in front of the QA team :face_with_spiral_eyes:.

1 Like

I learned my loop from one of the tutorial videos, I never knew it could cause any problems.

I have created a bool and set it to false, the problem is how can I make Unity know that for example, 4 loops have passed? Is there a way to + 1 to a int value with each loop, then when the int = 4 set the bool to true?

for (int i = 0; i < 4; i++){
    // Do stuff
}
2 Likes

Mine already has this:

for (int i = 0; i < hazardCount; i++)

All this does is change how many enemies spawn in the loop.

I modified my script slightly using a method I learned in a loop tutorial video. I added
‘int waveCount = 4’ then in the actual loop I put:

while (waveCount > 0)

waveCount--;

My understand was this should produce 4 loops then end. The result is it produces 2 loops then ends. It doesnt matter if I change the number to 4, 6, or anything it seems to always end after 2 loops :S

Post your whole code (with proper formatting), it’s hard to know what’s wrong without seeing it.

If you have a loop that’s meant to run for a set number of iterations, it’s clearer if you use a for loop like BoredMorman suggested, rather than a while loop. Neither is ‘right’ or ‘wrong’, but the for loop makes your intention clearer.

IEnumerator SpawnWaves ()
{
    yield return new WaitForSeconds (startWait);

    int numberOfWaves = 4;
    int numberOfHazardsPerWave = 10;

     for( int w = 0; w < numberOfWaves; w++ )
     {
        for( int h = 0; h < numberOfHazardsPerWave; h++ )
        {
            GameObject hazard = hazards [Random.Range (0,hazards.Length)];
            Vector3 spawnPosition = new Vector3(spawnValues.x, Random.Range(-spawnValues.y, spawnValues.y), spawnValues.z);
            Quaternion spawnRotation = Quaternion.identity;
            Instantiate(hazard, spawnPosition, spawnRotation);
            yield return new WaitForSeconds(spawnWait);
        }

        yield return new WaitForSeconds(waveWait);
    }
}

A for loop is designed to iterate a number of times, then stop. A while loop is designed to iterate indefinitely until some condition is met.

Change your while loop to a for loop.

2 Likes

Its ok I just figured out what is wrong. My loop counts the number of enemies not the waves, so putting 4 was way too low, as only 4 enemies were allowed to appear before it ended. I changed my int to 20 and now 4 waves will spawn then nothing :smile: