48: Balancing enemies
Objective: Add a weighted system for the Enemies
Now that we have a new enemy, let’s balance them so the basic enemy spawns a lot more than the ZigZag enemy.
The first thing we will do is add a property in the Enemy class to take a weight. We’ll make a public int _enemyWeight. I am leaving it public because later I’m thinking about implementing a system that’ll increase the weight of each enemy.
Next will be to move over to our spawn manager. We need to change our enemyPrefab to an array, so it’ll hold multiple enemies. Also, add a new variable for the enemy that got selected, as well has having a int variable to hold the total enemy weight.
Following this we’ll need a function to add all the weights of the enemies up. We’ll name this TotalEnemyWeightAmount. It uses a For loop to loop though all the enemies in the array and adds all their weights up and save to the total enemy weight
Next is a function that’ll select the enemy to spawn. In this function we need a random number generator, it’ll generate a number between 0 and totalEnemyWeight.
Than a foreach loop is used to go though each enemy again and see which enemy weight is greater than the random number. Which ever is greater than the random number will be saved into the selected enemy variable and passed on.
To finish it up, we need to call these functions. We’ll call the TotalEnemyWeightAmount in the StartSpawning function, so it’s not being recalculated every frame.
For the PickEnemyToSpawn will be called in the Coroutine that spawns our enemies.
In the Instantiate function we will swap out the enemyprefab that was there and add _selectedEnemy as shown above.
That’s a quick guide on how to create a little more balanced enemy system. Thank you for reading!