I’ve recently released my newest asset to the Unity Asset Store – Random Selector – Spawn and Loot randomizer. The asset provides an extremely efficient and fast randomizer, which can be used for spawning enemies, or deciding on players’ loot. Random Selector is based on the Alias Method algorithm, which supports selection of random items within a collection, based on weight.
In addition, the asset supports different random methods – Unity’s Random, System.Random, or a custom implementation. This allows developers to base their “randomness” based on anything they’d like, such as a web service.
The Alias Method algorithm
Here’s the definition of Alias Method in Wikipedia:
In computing, the Alias Method is a family of efficient algorithms for sampling from a discrete probability distribution, published in 1974 by A. J. Walker. That is, it returns integer values 1 ≤ i ≤ n according to some arbitrary probability distribution pi. The algorithms typically use O(n log n) or O(n) preprocessing time, after which random values can be drawn from the distribution in O(1) time.
Wikipedia, https://en.wikipedia.org/wiki/Alias_method
What does that mean? it means that we can create a list of items and “weights” (the chance an item will be selected) to the algorithm. It will perform a one-time “heavy” processing. After that, we can ask it for random items, and it will generate them VERY efficiently, and return the items with the expected frequency.
Using Random Selector in Unity
So how can you use Random Selector in Unity? The asset provides 3 modes (well, 2-and-a-half actually) of operation:
- Editor Only
- Code Only
- and Multi-Level
Editor Only mode
In this mode, you add the RandomSelectorScript
to one of the objects. You then configure the list of items to select from, and their weight. Invoking the GetItem
method will return the selected item, as well as raise the OnItemSelected
Unity Event.
Code Only mode
In this mode, you add a field of type RandomSelectorScript
to your script, programmatically add the items and their weights to the selector, and call GetItem
any time you want a new item.
Multi-Level mode
In this mode, you define a RandomSelectorScript
object, which selects one of it’s sub-RandomSelectorScript
items. Any number of levels can be achieved this way.
So… What can it be used for?
You can use the Random Selector anyway you want randomness in your game. Main scenarios include:
- Select the enemies to spawn in each wave of a Tower Defense game
- Select the dropped items when an enemy is dead in an RPG game
- Select the awarded cards when opening a chest in a Cards game
The Random Selector asset even includes a sample Cards game implementation in its demo scenes.