Balancing Powerup Spawning
This tutorial will cover balancing the spawning of powerups. This will make it so that powerups like ammo will spawn more often than the health powerup. This will be done by giving each powerup a percentage which will be how often the powerup will spawn relative to the others. Go to the SpawnManager script. Create a variable array for the spawn balancing percents.
[SerializeField] private int[] _powerupBalance;
Go to the Unity editor. in the SpawnManager give the new array the same size as the Powerups array. Then each element will be the percent chance it will spawn plus the previous element. So the 0 indexed element will be 20 so if the random number generates between 0 and less than 20 it will be the 0 indexed powerup. For the 1 indexed element it is 35% so add that to 20. It will be spawned if the number generated is between 20 and 55. This goes until the last element which is a 5% chance so between 95 and 100 will spawn the last powerup. Enter the appropriate numbers in the Inspector.
Now go to the SpawnManager script. Create a function called GetRandomPowerup that returns an int. In the function generate a number between 0 and 100 that will be used to compare which powerup should be generated. Loop through the elements in the powerupBalance array you created. Check to find which of the elements it is less than starting at the smallest. You will then return the element number which corresponds to the powerup that will be generated.
private int GetRandomPowerup()
{
int powerup = 0;
int randomNum = Random.Range(0, 100);
for (int i = 0; i < _powerupBalance.Length; i++)
{
if (randomNum < _powerupBalance[i])
{
powerup = i;
return powerup;
}
}
return powerup;
}
Last, you need to change where you generate the random int for the powerup to now call the GetRandomPowerup function that you just created.
int randomPowerUp = GetRandomPowerup();
This will now assign the powerup based on the distribution you assigned. You can continue to adjust your numbers to achieve the balance that you want.
-Chris