Writing · 2020 · 1 min
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
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 ITEM_RARITY_PROBS = {
, // 5% chance
, // 15% chance
, // 20% chance
, // 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
Comments
No comments yet. Be the first.