How do i make these class items more rare?

The title may not make a lot of sense, but basically i wanna do this:
Common - 90% chance
Rare - 20% Chance
Legendary - 5% Chance

This code seems to just give them out equally and idk how to make the higher tiers more random
heres the code:

local class = script.Parent

local mathh = math.random(1, 35)

class.Value = ""

local Found = false
while Found == false do
	print("retrying")
	local mathh = math.random(1, 35)
	
	if mathh == math.random(1, 10) then
		print("Got Common")
		class.Value = "Common"
		Found = true
	elseif mathh == math.random(1, 35) then
		print("Got Rare")
		class.Value = "Rare"
		Found = true
	elseif mathh == math.random(1, 60) then
		print("Got Legendary")
		class.Value = "Legendary"
		Found = true
	else
		class.Value = ""
	end
	task.wait()
end

Thanks! ive never made Tier-Based RNG before

1 Like

Why are you checking if mathh is equal to different math.random values? You could just do it like this:

local RandomNumber = math.random(1,100) -- Gives us a random number from 1 - 100 

if RandomNumber >= 1 and RandomNumber <= 20 then -- All numbers from 1 to 20 are considered this tier, you could also change the range to include more or less numbers, repeat this process for other tiers **WITHOUT** repeating numbers. 
Class.Value =  "Common"
end

What not to do:

local RandomNumber = math.random(1,100)

if RandomNumber >= 1 and RandomNumber <= 20 then 

elseif RandomNumber >=20 and RandomNumber <= 40 then 
-- Both these tiers repeat the number 20, so rolling a 20 will be both a common and this tier
end

You should also not do this:

local RandomNumber = math.random(1,100)

if RandomNumber >= 1 and RandomNumber <= 20 then 
-- Any number from 1 to 20 is picked
elseif RandomNumber >=1and RandomNumber <= 40 then 
-- Any number from 1 to 40 is picked
-- It could work out because numbers from 1-20 are eligible to be picked for the first if statement (as in it is true) and because that if statement is the first one read you should be fine, but this could lead to issues 
end
2 Likes

I agree with @Bovious. To help you with your rarity script though, you can use this simple weighted rarity script that works.

local RarityList = {
	["Common"] = 90; -- Change percentage to your likings
	["Rare"] = 20;
	["Legendary"] = 5;
}

local function GetRarity()
	local TotalWeight = 0
	
	for i, Chance in pairs(RarityList) do
		TotalWeight += Chance
	end

	local RandomChance = math.random(1, TotalWeight)
	local CumulativeChance = 0

	for Rarity, Chance in pairs(RarityList) do
		CumulativeChance += Chance
		
		if RandomChance <= CumulativeChance then
			return Rarity
		end
	end
end

while wait(1) do
	print("Got "..GetRarity())
end