So i’m currently working on a Pet System for my fanbase on YouTube, but i’m having an issue.
When I buy a pet, it somehow gives me a random number of pets.
Sometimes it works perfectly, so it gives me 1 pet as intended, but sometimes it gives me 2 or 3.
Any idea?
local rep = game:GetService("ReplicatedStorage")
local remotes = rep:WaitForChild("Remotes")
local buyEggRemote = remotes:WaitForChild("BuyEgg")
local petsFolder = rep:WaitForChild("Pets")
local rarities = require(script.Parent:WaitForChild("Rarities"))
------------------------------------------------------
buyEggRemote.OnServerEvent:Connect(function(player, currency, cost, egg)
local leaderstats = player:WaitForChild("leaderstats")
local character = player.Character
local humanoidRootPart = character:WaitForChild("HumanoidRootPart")
local random = math.random(0,100)
local pets = petsFolder:FindFirstChild(egg)
local function BuyPet(petAmount)
local function Buy()
leaderstats:FindFirstChild(currency).Value -= cost * petAmount
leaderstats:WaitForChild("Pets").Value += petAmount
end
local function ChooseRandomPet(rarity)
local petNum = pets:FindFirstChild(rarity):GetChildren()
local pet = petNum[math.random(1, #petNum)]:Clone()
print(pet.Name)
pet.Parent = workspace
pet.CFrame = humanoidRootPart.CFrame
end
if random <= rarities.Common then
Buy()
ChooseRandomPet("Common")
end
if random <= rarities.Uncommon then
Buy()
ChooseRandomPet("Uncommon")
end
if random <= rarities.Rare then
Buy()
ChooseRandomPet("Rare")
end
if random <= rarities.Epic then
Buy()
ChooseRandomPet("Epic")
end
if random <= rarities.Legendary then
Buy()
ChooseRandomPet("Legendary")
end
end
if leaderstats:WaitForChild("OwnsTripleGamepass").Value == false then
BuyPet(1)
elseif leaderstats:WaitForChild("OwnsTripleGamepass").Value == true then
BuyPet(3)
end
end)
im guessing that the rarities are number values?
It could be that it chose a random value between two rarities so it gave you two, im not sure though, could you give more info though?
Try replacing all of the “if random <= rarity then” statements with this.
local RaritiesForThisEgg = {{"Common",rarities.Common},{"Uncommon",rarities.Uncommon},{"Rare",rarities.Rare},{"Epic",rarities.Epic},{"Legendary",rarities.Legendary}}
table.sort(RaritiesForThisEgg,function(i,i2)
return i2[2] > i[2]
end)
local stop = false
for i = #RaritiesForThisEgg,1,-1 do
if stop == false then
local v = RaritiesForThisEgg[i]
if random <= v[2] then
Buy()
ChooseRandomPet(v[1])
print("horray!")
stop = true
end
end
end
edit: Only have this one time, it should take care of every rarity.