Creating A Basic Loot Table For Power-Ups
Rather than relying on random spawns with equal chance, let’s add some weight to spawn chances.
Today’s objective: Create a weighted loot spawner to replace the completely random loot spawner.
Let’s do it!
Rather than just needing a GameObject to spawn, each power-up now also needs a numeric value to indicate it’s spawn chance.
Create a new “LootTable” script. Change it from a “class” to a “struct”, making it easier to use as a variable. Inside that struct, create another struct like this:
Add an array of type “LootTableObject” inside “LootTable”.
Inside “LootTable”, create a function to return the combined total of all spawn chances in the array.
Now create a function to return a random GameObject from the array, based on spawn chance weight.
Add a ForEach loop to the function too.
Finally, add an error log to the end of the function, in case anything goes wrong, which should be impossible.
Now, I use a script called SpawnManager to manage spawning everything. In that script, I’ve made a variable “_powerups” of type “LootTable”.
And when I want to spawn a power-up, I simply use “_powerups.GetRandomWeightedSpawnable()”.