Creating a simple Wave Spawner.
For the third challenge, “Implement wave sequencing of enemies with more
enemies coming each wave.”. While there’s a lot of wave spawning help and tutorials out there, I decided to try figuring it out on my own and I think I came up with an acceptable version and I think with a little bit of tweaking, we’ll have a steadily increasing level of challenge and difficulty for the game.
First, I put in a new text element onto the canvas and called it Level_Text with the text “Level : 0” in it. Then turned it off because we’ll turn it back on at the beginning of each level.
As we head into the spawner, the very first thing when we hit the asteroid to start the waves, we’ll kick things off by showing what level we’re on.
ShowLevel is very much like the other UI updates, we assign the text to the object, turn it on, wait 1 second, and turn it off again.
Here’s the entire wave spawning engine. I set maxEnemies to 3 so the for loop will wait 3–4 seconds in between each enemy before picking a random spot and instantiating it.
If you notice right before instantiating, I created the ChooseEnemy function to be a little more readable. here. Let’s take a look at it now before coming back:
So depending on what level you are on, it will limit the amount of choices you have for enemies. level 1 will only choose between a random range of enemy 1 and enemy 1. Level 2 will choose between enemy 1 and enemy 2, level 3, enemy 3 and so on… To balance things out, I even started placing the same enemy in levels 1–3 to keep things simple for the player until he reached level 4, where a new enemy would be finally introduced.
This is how harder enemies appearing later on in the wave spawning process was done here. Once we reach the end of the amount of prefabs, say, level 15, we force it back to the amount of enemies we have, 12, so no errors will occur in our enemy choosing code. OK, Back to the main section!
after instantiation, we increase a variable called enemiesSpawned. If this variable reaches the _maxEnemies variable, we’re done with this level! we reset enemiesSpawned to 0, reduce the amount time to wait before new enemies are spawned by a fraction, and we increase the amount of maxEnemies every other level, of which we also increase.
Here it is in action!