Pet Script Help

Hello fellow devforum users! I made a rarity system, but for some odd reason the pet doesn’t get cloned(and I need it to be). All help is appreciated!

local folder = game.ReplicatedStorage.Pets

local pets = {
	{name = "DumbFloppa", rarity = 60/100, FloppaType = folder.DumbFloppa},
	{name = "Floppa", rarity = 9/100, FloppaType = folder.Floppa},
	{name = "SirFloppa", rarity = 30/100, FloppaType = folder.SirFloppa},
}

local totalWeight = 0
for _, item in ipairs(pets) do
	totalWeight = totalWeight + item.rarity
end

local function getRandomPet()
	local randomValue = math.random() * totalWeight
	local cumulativeWeight = 0

	for _, item in ipairs(pets) do
		cumulativeWeight = cumulativeWeight + item.rarity
		if randomValue <= cumulativeWeight then
			return item.FloppaType
		end
	end
end

game.ReplicatedStorage.PetRemotes.GetPet.OnServerEvent:Connect(function()
	getRandomPet():Clone()
end)
3 Likes

It was a problem with how you set up the randomness. Try this:

local folder = game.ReplicatedStorage.Pets

local pets = {
	{name = "DumbFloppa", rarity = 60, FloppaType = folder.DumbFloppa},
	{name = "Floppa", rarity = 9, FloppaType = folder.Floppa},
	{name = "SirFloppa", rarity = 30, FloppaType = folder.SirFloppa},
}

local function getRandomPet()
	local TotalWeight = 0 
	
	for I, X in pets do TotalWeight += X.rarity end
	
	local Rand = Random.new(os.clock() * math.random(1,10))
	local RandomValue = Rand:NextInteger(1, TotalWeight)
	
	local PickedFloppa = nil
	
	for _, item in pets do
		if RandomValue <= item.rarity then
			PickedFloppa = item.FloppaType
			break
		else	
			RandomValue -= item.FloppaType
		end
	end

	return PickedFloppa
end

game.ReplicatedStorage.PetRemotes.GetPet.OnServerEvent:Connect(function()
	getRandomPet():Clone()
end)

Disclaimer: I’m on mobile so it might not fully work or might have errors

3 Likes

Thanks for the help! I will get straight to testing this. Even if it has bugs lol.

2 Likes

Yea let me know if you encounter any problems

1 Like

After a while I decided to redo the whole rarity system, it works now.

1 Like

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