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.
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.