Pick Random Item Based on Probability


I was working on my game recently and realized my random item code doesn’t randomly select items the correct way.

For example in my game, when entering a store it randomly fills the store with items. It should mostly pull in common items but if you’re lucky it’ll have some rare items. The best way to handle this is like so:

Create enum

public enum Rarity {
    Hidden = 0,
    Basic = 1,
    Common = 2,
    Uncommon = 3,
    Rare = 4,
    VeryRare = 5
}

Static Array of Probabilities

Create a static array of your items and the probabilities. All the values added up should equal 100.

public static KeyValuePair<Rarity, int>[] ITEM_RARITY_PROBS = {
    new KeyValuePair<Rarity, int>(Rarity.VeryRare, 5), // 5% chance
    new KeyValuePair<Rarity, int>(Rarity.Rare, 15), // 15% chance
    new KeyValuePair<Rarity, int>(Rarity.Uncommon, 20), // 20% chance
    new KeyValuePair<Rarity, int>(Rarity.Common, 30), // 30% chance
    new KeyValuePair<Rarity, int>(Rarity.Basic, 30) // 30% chance
};

Probability Calculation

As the loop is ran the cumulative value increases therefore making the next chance higher. I won’t go into the details but the math works out so the other items have a proper probability of being chosen.

public Rarity GetRandomRarity() {
    int cumulative = 0;

    for (int i = 0; i < ITEM_RARITY_PROBS.Length; i++) {
        cumulative += ITEM_RARITY_PROBS[i].Value;

        if (UnityEngine.Random.Range(0, 100) < cumulative) {
            return ITEM_RARITY_PROBS[i].Key;
        }
    }

    return Rarity.Basic;
}

Related Posts

Test Your Chinese Using This Quiz

Using Sidekiq Iteration and Unique Jobs

Using Radicale with Gnome Calendar

Why I Regret Switching from Jekyll to Middleman for My Blog

Quickest Way to Incorporate in Ontario

Creating Chinese Study Decks

Generating Better Random Numbers

Image Magick Tricks

My Game Dev Process

Unit Manager Code Snippet