Unity Random Number With Decreasing Probability

Unity random range with probability in C# | Blog Post 3DModelsCC0

Creating a C# number generator method that basically works like Random.Range() in Unity Engine with the possibility of assigning a weight to skew the ending result in either direction is an extremely useful tool in game development when creating different looting and/or scoring systems.

Feel free to copy the method below and make sure to see the different examples of usage with visual graphs.

Skewed Random Range:

float SkewedRandomRange(float min, float max, float weight)
    float rnd = Mathf.Pow(Random.value, weight);
    float index = (min + rnd * (max - min + 1));
    return Mathf.Clamp(index, min, max);



SkewedRandomRange(min, max, weight);

min - Smallest possible number.

max - Largest possible number.

weight - Skewing of the result.

- If weight is 1, the method will not skew the result.

- If weight is above 1, it will skew the result with an increasing probability towards the min value.

- If weight is anything between 0 and 1, it will skew the result with an increasing probability towards the max value.


Most of you probably will be best off using anything below 0.5f as a weight to achieve the most predictable type of slope as it doesn't weigh the starting value so heavily. See the examples below.



These graphs will show you how using different weights will affect the ending result. All of the following tests were executed a million times within the range of (1, 10).

SkewedRandomRange(1, 10, 0.5f);
Unity random number with a skewed probability.

SkewedRandomRange(1, 10, 0.3f);

Unity random number with a probability slope.

SkewedRandomRange(1, 10, 1.1f);

SkewedRandomRange(1, 10, 1.25f);

SkewedRandomRange(1, 10, 2f);