I've been working on this section of code in the main Gameplay.cs script of my Unity 2D project for a long while now and no matter which way I change it and shift things around, it either causes Unity to lock up on Play or, after some tweaking, will instantly go from Wave 0 to Wave 9. Here is my original attempt, which causes Unity to freeze on Play. I do not understand why this happens and would like some insight on where my logic has gone wrong.
I am trying to achieve the following:
- On Play, game waits startWait seconds.
- After startWait, game goes into SpawnWaves() method and waits waveWait seconds between every wave and increments the wave count by one during each wave.
- Every wave spawns zombieCount number of enemies and waits spawnWait seconds between each zombie is spawned.
private float startWait = 3f; //Amount of time to wait before first wave
private float waveWait = 2f; //Amount of time to wait between spawning each wave
private float spawnWait = 0.5f; //Amount of time to wait between spawning each enemy
private float startTimer = 0f; //Keep track of time that has elapsed since game launch
private float waveTimer = 0f; //Keep track of time that has elapsed since last wave
private float spawnTimer = 0f; //Keep track of time that has elapsed since last spawn
private List<GameObject> zombies = new List<GameObject>();
[SerializeField]
private Transform spawnPoints; //The parent object containing all of the spawn point objects
void Start()
{
deathUI.SetActive(false);
//Set the default number of zombies to spawn per wave
zombieCount = 5;
PopulateZombies();
}
void Update()
{
startTimer += Time.deltaTime;
if (startTimer >= startWait)
{
waveTimer += Time.deltaTime;
spawnTimer += Time.deltaTime;
SpawnWaves();
}
//When the player dies "pause" the game and bring up the Death screen
if (Player.isDead == true)
{
Time.timeScale = 0;
deathUI.SetActive(true);
}
}
void SpawnWaves()
{
while (!Player.isDead && ScoreCntl.wave < 9)
{
if (waveTimer >= waveWait)
{
IncrementWave();
for (int i = 0; i < zombieCount; i++)
{
if (spawnTimer >= spawnWait)
{
Vector3 spawnPosition = spawnPoints.GetChild(Random.Range(0, spawnPoints.childCount)).position;
Quaternion spawnRotation = Quaternion.identity;
GameObject created = Instantiate(zombies[0], spawnPosition, spawnRotation);
TransformCreated(created);
spawnTimer = 0f;
}
}
waveTimer = 0f;
}
}
}
I am a beginner and understand my code may not follow best practice. I also have a working enemy spawner that uses Coroutine and yield returns, but would like to get this version of my enemy spawning working.