- Home /
IEnumerator's did not read "bool" after yield return new WaitForSeconds.
Hi, I started using Unity in early March 2020 and trying out coroutine. Im working on a tower defense game, most of the code are base on Brackey's tutorial.
In the script there are suppose to have 3 types of orcs(speed, common, tank). They are spawn in orders (from "SpawnWaveSpd" to "SpawnWave" to "SpawnWaveTank").
I use bool to keep track which type of orc is spawning and which is not. The SpawnWaveSpd's bool (spdOrcIsSpawning) & Spawnwave's bool (comOrcIsSpawning) is working fine. Only when it comes to the end, the SpawnWaveTank's bool (tankOrcIsSpawning) keep at "true" after complete spawning.
Am I doing it right or is there something Im miss out?
//Speed Orc spawn 1st
IEnumerator SpawnWaveSpd(Wave _wave)
{
state = SpawnState.Spawning;
spdOrcIsSpawning = true;
for (int i = 0; i < _wave.countSpd; i++)
{
SpawnSpdOrc(_wave.enemySpd);
yield return new WaitForSeconds(0.5f / _wave.rate);
}
spdOrcIsSpawning = false;
yield return StartCoroutine(SpawnWave(enemyWaves[nextWave]));
}
//Common Orc spawn 2nd
IEnumerator SpawnWave(Wave _wave)
{
comOrcIsSpawning = true;
for (int i = 0; i < _wave.countCom; i++)
{
SpawnOrc(_wave.enemyCom);
yield return new WaitForSeconds(0.5f / _wave.rate);
}
comOrcIsSpawning = false;
yield return StartCoroutine(SpawnWaveTank(enemyWaves[nextWave]));
}
//Tank Orc spawn last
IEnumerator SpawnWaveTank(Wave _wave)
{
tankOrcIsSpawning = true;
for (int i = 0; i < _wave.counttank; i++)
{
SpawnOrcTank(_wave.enemyTank);
yield return new WaitForSeconds(0.5f / _wave.rate);
}
tankOrcIsSpawning = false;
state = SpawnState.Waiting;
}
Using bool is not optimal for more than 2 possible states. Here you have 3 types of waves, thus in each wave you are must change state of 3 different bools. What happens when you add more wave types, yes, adding more bools in each method. Which isn't optimal. There are plenty of other ways to keep track of a wave type. You can use enum or, even better, create a custom data type for each wave which can contain all useful info about the wave, such as type, max enemies, rate, prefabs used, basically everything that can fully describe the wave, so then you can have 1 single coroutine which takes this wave object as a parameter and then handle wave spawning using the info from the wave data object.
Answer by MurphyMurph_21 · Nov 20, 2020 at 07:28 AM
@BLAK3C maybe add yield return WaitForEndOfFrame()
on the last coroutine after state = SpawnState.Waiting