Better random generation

My goal is to randomly generate items in my map. This is the script I have so far

function item.GenerateItemsInMap()
	for _, itemType in pairs(ItemSpawns:GetChildren()) do
		for _, itemSpawn in pairs(itemType:GetChildren()) do
			local Chance = math.random(1, 5) -- 1 in 5 chance to spawn

			if Chance ~= 1 then continue end
			
			local newTool = ItemCopies[itemType.Name]:GetChildren()[math.random(1, #ItemCopies[itemType.Name]:GetChildren())]:Clone()
			newTool.Parent = CurrentItems
			newTool:PivotTo(itemSpawn.CFrame)
		end
	end
	
	NETWORK.FireAllClients("SetupItems", CurrentItems)	
end

The way it works is: it goes through all the spawn locations for items for a certain type e.g “consumable” or “weapon” then it does a math.random to give a random chance of it spawning. It also gets a random item of the certain type too.

However I want to make this a bit more advanced where every single item has a unique rarity of spawning and I want the different types of items have a rarer or more common spawn rate.

How can I achieve such a mechanic?

1 Like

For a rarity system, you could create a value in each of your objects, which is checked in the script and adapted according to it.
(this value would for example change the math.random for a lower or higher chance)

This doesnt really help me, I just did the same thing in my script but the same rarity for all values

Your goal is to have different rarities for your items, no ?

This is probably going to need weighted probability. Here’s a thread with some methods for it. With weighted probability all probabilities should add up to 1 or 100%, it’s been a while since I’ve messed with it in Roblox but it’s doable

How does it work? From what I can tell I could use this like this:

Get a rarity from the roll function, select all items of the item type with that rarity, select a random item from it.

How does it work though from what I can see in the example he makes common 100% but wouldn’t that mean that everything else will be impossible to roll because probabilities have to add up to 1 or 100%

It’s called weighted chance which is calculated by dividing the weight of an item by the total weight of all the items.

Item Weight Probability
A 10 20%
B 20 40%
C 20 40%
Total 50 100%

I’ve made a module specifically for that: WeightedRandom - A weighted random module with a built-in luck system

It has extra built in methods and examples in the post itself.

This seems useful for unboxing mechanics. Thanks anyway I’ll probably use it I guess.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.