Unity Weighted Random

Random number generation is used a lot of times in videogames. The main idea is that we want to generate a random number in the range [x, y] and use it for any purpose. Let look an example from Unity point of view:

We have an array of available items to spawn, and somewhere in our code we do something like this: int index = Random.Range(0, array.Length);

This way we’re going to get a random number, and use it to spawn the item in position index of the array. (just what we want :)) The cons of this method is that all the items in the array have the same probability to be spawned, and sometimes we don’t want this behaviour. Sometimes we want to define a probability for each of the available items. Here it comes Weighted Random.

Weighted Random allow us to define a weight for each item in the array of available items, in consequence, we modify the probability of that item to be spawned. ( I have just used it to modify the probability a life is spawned in a game. I did’t want a life to be spawned with the same probability as a coin :)).

Weighted Random

So, i have uploaded a little Unity project to my github with several classes for generating weighted random integers. Weighted Random

Hope it is useful ^^

Leave a Reply

Your email address will not be published. Required fields are marked *