- Home /
How to get if all all objects are destroyed to start another wave
I am making a simple shooter. I want the following: to keep track of current enemies. if there are no enemies I want to start the new wave. My game controller code currently looks like this: using System.Collections; using System.Collections.Generic; using UnityEngine;
public class GameController : MonoBehaviour {
public GameObject[] Bosses;
public GameObject[] Enemies;
public int EnemyCount = 3;
public float SpawnWait = 0.1f;
public float StartWait = 1f;
public float WaveWait = 1f;
private float waveNumber = 1;
void Start () {
StartCoroutine(SpawnWaves());
}
private IEnumerator SpawnWaves()
{
yield return new WaitForSeconds(StartWait);
while (true)
{
Debug.Log("Starting Wave");
if (GameObject.FindGameObjectWithTag("Enemy") != null)
continue;
if (waveNumber % 3 == 1 && waveNumber > 1)
{
Debug.Log("Sending New Enemy");
float spawnCoordY = Random.Range(-4, 4);
Vector2 spawnPosition = new Vector2(5, spawnCoordY);
System.Random random = new System.Random();
int enemyToSpawnIndex = random.Next(0, Bosses.Length);
GameObject currentEnemy = Instantiate(Bosses[enemyToSpawnIndex], spawnPosition,
Quaternion.identity);
}
else
{
for (int i = 0; i < EnemyCount; i++)
{
float spawnCoordY = Random.Range(-4, 4);
Vector2 spawnPosition = new Vector2(5, spawnCoordY);
System.Random random = new System.Random();
int enemyToSpawnIndex = random.Next(0, Enemies.Length);
GameObject currentEnemy = Instantiate(Enemies[enemyToSpawnIndex], spawnPosition,
Quaternion.identity);
yield return new WaitForSeconds(SpawnWait);
}
EnemyCount += 2;
}
waveNumber++;
yield return new WaitForSeconds(WaveWait);
}
}
}
As you can see, I check if all enemies have been destroyed by seeking for enemy with tag and if no enemy is found I start next wave. For unspecified reason it has some problems. Sometimes it freezes the game (and the editor itself). I know the problem is there because when I comment out that line it works well. Please tell me what is the main problem of it ? and also if there is a better practice of doing what I want do not hesitate to also tell it to me.
Answer by Dragate · Oct 17, 2017 at 11:29 AM
If "Enemy" is found, you "continue;", which makes it return to "while(true)". Basically, a loop that will not finish until it finds an "Enemy" in the same frame (which causes freeze). Instead of using continue, use
yield return new WaitForSeconds(delay); //check again after some delay
or
yield return null; //check again in the next frame