How would I make something appear more depending on the rarity?

I’m working on a thing where a store selects random stock. I can do that no problem. Each item that can be sold has a rarity, there are five different rarities.

I have no idea how to go about this. If I didn’t have to deal with rarities, then I would just pick a number from 1 and however many items there are. But I can’t do that. I know I haven’t supplied any code, but I have no idea where to begin.

I tried googling “How to code rarity systems” or “How to code Loot Boxes” but I couldn’t find anything.

6 Likes

You’re going to want to use a Weighted randomization setup. Basically, assign each item a “weight” value. Whenever the script wants to choose an item, it chooses a random number between 1 and the sum of the weights of all possible items. Then, you loop through a list of the items with a counter to determine which weight lies within which item.

An item with more weight will appear more often than an item with less weight.

Example:

local Items = {
	{"Table",1},
	{"Lamp",5},
	{"Chair",10},
}
local TotalWeight = 0

for _,ItemData in pairs(Items) do
	TotalWeight = TotalWeight + ItemData[2]
end

local function chooseRandomItem()
	local Chance = math.random(1,TotalWeight)
	local Counter = 0
	for _,ItemData in pairs(Items) do
		Counter = Counter + ItemData[2]
		if Chance <= Counter then
			return ItemData[1]
		end
	end
end

for i=1,10 do
	print(chooseRandomItem())
end

You should notice that “Chair” is chosen very often, “Lamp” is chosen semi-often, and “Table” is a very rare occurrence.

86 Likes

Please. I get the jist of what you say, but an example would make more sense and how to utilise it.

3 Likes

Thank you! Say I have another item with 1 weight, will that still work?

3 Likes

Yep. The higher the weight, the higher the rarity. Try to stick with whole numbers, I don’t think this works with decimals.

4 Likes

I think you might of contradicted yourself as in your code, the higher the number, the more common it appears. ;p thank you very much tho.

4 Likes

Whoops! I meant higher weight, lower rarity… thing appears more often. You get what I mean :^)

13 Likes