How would I make a rarity / chance system?

So I’m making a game kinda like SCP 3008. And I’m trying to make a rarity system on the different rooms. Example: Bedroom’s chance of spawning = 5% and Cafeteria’s chance of spawning = 1%.

I have tried to make this using a Table. The given numbers are the chance they have to spawn.

local Rooms = {
	"AppartmentModel" == 5; -- Chance for it to spawn
	"BathRoom1" == 5;
	"BedRoom" == 5;
	"BedRooms" == 5;
	"Beds" == 5;
	"Carpets" == 5;
	"ChildrensRoom" == 4;
	"Coutches" == 5;
	"Kitchen" == 3;
	"Kitchen 2" == 3;
	"Kitchen3" == 2;	
	"LivingRoom" == 5;
	"MasterBedRoom" == 4;
	"Moving" == 5;
	"Office1" == 5;
	"Outdoors" == 4;
	"Pellets" == 2;
	"Storage" == 1;
	"Tables" == 5;
	"TeenRoom" == 5;
	"TwinBedroom" == 5;
}

Currently, my system just picks a random room and I don’t like that as I want to be able to make rare rooms with special game objects.

local rooms = game.ReplicatedStorage.RoomsClean:GetChildren()
local randomroom = rooms[math.random(1, #rooms)]:Clone()

If anyone out there has any idea of how I could make this “spawn chance” system please reply.

2 Likes

This can be answered in a simple google search: How to make a random loot table - YouTube

Yeah but he doesn’t use a table to do it. Wait my bad he does

Doesnt work with what im trying to do.

function GetRandomItem()
	local Sum = 0
	for RoomName,Chance in pairs(RoomsChances) do
		Sum += Chance
	end
	local RandomNumber = math.random(Sum)
	for RoomName,Chance in pairs(RoomsChances) do
		if RandomNumber <- Chance then
			return RoomName -- Error from here
                else
                       RandomNumber -= Chance
		end
	end
end

It gives me. Argument 1 missing or nil

You have a typo

function GetRandomItem()
	local Sum = 0
	for RoomName,Chance in pairs(RoomsChances) do
		Sum += Chance
	end
	local RandomNumber = math.random(Sum)
	for RoomName,Chance in pairs(RoomsChances) do
		if RandomNumber <= Chance then
			return RoomName -- Error from here
        else
            RandomNumber -= Chance
		end
	end
end

It is also worth noting that since the values don’t change you only have to calculate sum once.


local Sum = 0
for RoomName,Chance in pairs(RoomsChances) do
	Sum += Chance
end

function GetRandomItem()
	local RandomNumber = math.random(Sum)
	for RoomName,Chance in pairs(RoomsChances) do
		if RandomNumber <= Chance then
			return RoomName -- Error from here
        else
            RandomNumber -= Chance
		end
	end
end

But you probably won’t actually see the performance improvement with how slight it is. Making it practically useless.

3 Likes

You wrote <- instead of <= - as @tlr22 said you made a typo

A search often helps:

1 Like

Thanks this fixed the problem cant thank you enough!

1 Like