Random Item Spawn using array (with item rarity variable)

This may be a simple question, but since I’m learning C# as I go and Google is not my friend today, I’ll ask it anyway.

I’m trying to write a script (attached to a Spawner object) that will randomly spawn an item from an array of GameObjects, which is fine, but I also want each item to have a different chance of spawning based on that object’s rarity. The thing I’m not sure about is how to access/apply such a variable in order for it to actually affect an item’s chance of spawning, or if that’s even possible with a simple Random.Range. What is the best way to go about this?

Thanks in advance. :wink:

simple random.range-
obj = objarray[rnd(0, objarray.length)]
if (obj.chance > rnd(0,100)) → spawn

Don’t think that’s exactly what I need. Say I want food to spawn in a house with a:

30% chance of spam
20% chance of beans
10% chance of peaches
10% chance of mixed nuts
30% chance of nothing

Won’t calling a completely random object, THEN checking its rarity throw off those odds? If all objects are equally likely to be selected by the Random.Range before rarity is taken into account then the ones with higher rarity actually have their true spawn chance boosted.

For a brief moment I thought I had an idea, where by placing Spam in my array 3 times (if that’s allowed), and Peaches once, Spam would be exactly 3 times as likely to spawn with a Random.Range call. I quickly realised how unnecessarily large and confusing my arrays would get. Not to mention all the horrible hard coding that would entail. Best pretend I never said that lol :sunglasses:

So, any wizards here know a way to get all of the objects’ rarity values into a single calculation? Just like a switch, but not every case is equally as likely.

Ah don’t worry guys, old mate Google has come through once again. Here’s my answer for reference purposes: