Geek Culture
Published in

Geek Culture

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 “[System.Serializable]” to both Structs to make them serialized for Inspector modification
If you want, add a range attribute with a suitable maximum to “Chance”, to make the Inspector look nicer.

Add an array of type “LootTableObject” inside “LootTable”.

The LootList won’t change in-game, so an Array is better than a List.

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.

Two vital variables inside the function

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”.

Because they are serialized, they structs appear in the Inspector to fill

And when I want to spawn a power-up, I simply use “_powerups.GetRandomWeightedSpawnable()”.

Spawn a power-up based on all weights
Make sure to fill the array in the Inspector, and that at least one Chance is above zero.

--

--

--

A new tech publication by Start it up (https://medium.com/swlh).

Recommended from Medium

Pocket Infrastructure Bootstrap Program Brief

Lessons Learned — 5 Steps for creating React Native App from scratch

What an Open Source Community Taught me About Asking

10 Key Factors to Ensure Software Project Success | Seamgen Blog

CSS4 Selectors: What Can We Expect?

Simulators, Emulators, or Real Devices: Which is the Best for Mobile Testing?

3 Main Challenges of Adopting Scrum

CS373 Fall 2021 Blog 3

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Vincent Taylor

Vincent Taylor

Unity game developer / C# Programmer / Gamer. Australian (Tasmanian) indie games developer for 10+ years. Currently looking for games industry employment.

More from Medium

The Fourth Player Challenge: Problem Solving and Jumping

Adding a thruster speed boost on keypress

More Productive Editor Layout in Unity

What is a Control Track in Timeline