top of page

Tip: Unity's secret visual mathematical transform (awesome, easy random numbers)

The Random function is the way to add variety to your game, rolling a virtual dice to allow you to pick one of several options. However, we need greater control than just random numbers, such as when dropping random loot based on rarity.

Here I've got an array of 5 objects of increasing rarity and value. I use a random number from 0.0 to 1.0 (Random.value) to select from this array.

If a treasure chest or boss is killed and I call this 12 times to drop items, the result would look something like this...

The problem here is that 'rare' items are equally likely as 'common' items. We need a way to set the probabilities to make rare items less likely. There exist ways to do this in code, including a free Random From Distributions asset on the store that I was using, but I had a moment of inspiration and realised that, more intuitive than all of these, we can repurpose Unity's appalling named 'Animation Curves' and visually represent our distribution.

The Animation Curve doesn't have to be used for Animation but can be used as generic interface to map an input onto an output, and it's very simple to use. Just add a public field to your class of type Animation Curve. This adds an editable curve to the inspector.

To perform a transformation, call your curve's Evaluate() method.

This takes the input value as the x axis and converts it to the output value defined by the y axis. If the random number is 0.57, the default straight line curve would output 0.57 which would map to a Blue item from our array. The default line doesn't change the input, so we get the same random distribution as before...

Now by adjusting the curve, we can change the distribution in a very visual way. To make rare items actually rare, we can use a steep curve...

Or we can focus on a large amount of a middling values (which for ionAXXIA is perfect for asteroid sizes, with most being middling sized but with a few tiny or large rocks)...

You can also limit your sampling with a Random.Range() selection.

Animation Curves have quite a few advantages over trying to manage distributions in code.

  • It's highly visible so you can see the distributions.

  • It gives full control without needing things like lists of probability values.

  • If you use the same 0..1 range for each curve, you can chain curves together. You can have one curve for your treasure chest defining low rarity, and then another for your level defining higher rewards, and pass the output from one curve to the input of another...

Anywhere you want 'randomised' values in your game, consider using a curve to help shape the variation.

Featured Posts
Check back soon
Once posts are published, you’ll see them here.
Recent Posts
Archive
Search By Tags
No tags yet.
Follow Us
  • Facebook Basic Square
  • Twitter Basic Square
  • Google+ Basic Square
bottom of page