Balanced loot spawner in Unity

Daniel Kirwan
3 min readMay 5, 2021

Objective: To create a more balanced loot spawner for a 2D space shooter.

I now have all of the power-ups that I want in the early version of the game. I now want to create a system that allows for more balanced gameplay. To do this I created a system that works on a power-ups given chance percentage.

I needed four variables to create the system and one has already been made.

  1. Array of powerup prefab gameobjects
  2. int array for the powerup weights
  3. int for the total weight of all the items in the item array(2)
  4. int for a random number (0, totalweight)

Next thing to do is to set up the method for picking a power-up to spawn.

First I am still picking a random y position for the power-up to spawn in. Next I am setting the randomNumber variable to a Range between 0 and the totalWeight of the table, which in my case is 100.

Next is a for loop to decide which power-up is spawned.

  1. Check if the randomNumber is less than the number in the array called table at position [i].
  2. If the above check is true I spawn the power-up at position [i] in the power-up table (make sure your loot/items to spawn are in the correct order in the powerups array).
  3. Else I am taking away the table[i] int from the randomNumber.

As an example, if the randomNumber is 61 then the else statement will run. It will take away table[i], which would be 40 on the first iteration. This will make the randomNumber = 21. On the next run through the loop it will now check is 21 < table[i], the next number in my array is 20. So, the answer is false so the else statement will run again, this makes randomNumber = 1.

On the next check, the randomNumber which is now 1 is less than table[i], the item here is 10. This will now spawn the speed power-up and will then return out of the for loop.

You can see the new weighted spawner in action above. This will work for other games as well as a 2D game. If you’re making an RPG you could use it to spawn a random item when an enemy is killed etc. There are many situations you could use a random loot generator in.

Good luck with your game development.

--

--