This pet hatching script I am using will return nil occasionally. I have literally no idea why this happens, and all of the print statements come out right, except it will just (seemingly at random) return nil from time to time. It is important to note that, when I use a predefined table instead of the method I am currently using, it does not return nil. My only guess would be to use a wait system, but I can’t even figure that out. Anyone have any ideas?
Module:
local config = {}
config.Price = 25
local folder = game.ReplicatedStorage:WaitForChild("PetResults"):WaitForChild("Basic Egg") -- Get the Basic Egg folder from ReplicatedStorage
local foldtable = folder:GetChildren()
config.HatchablePets = {} -- Initialize an empty table
-- Iterate over each folder inside foldtable
for i = 1, #foldtable do
local subFolder = foldtable[i]
local subFolderChildren = subFolder:GetChildren()
-- Iterate over the children of the current subFolder and add their names to the HatchablePets table
for j = 1, #subFolderChildren do
local child = subFolderChildren[j]
if child:IsA("Model") and child.Name then
print("Added "..child.Name.." to Table!")
table.insert(config.HatchablePets, tostring(child.Name))
end
end
end
print(config.HatchablePets)
config.Chances = {
Common = 70,
Uncommon = 25,
Rare = 4.5
}
return config
Server Script:
-- This is a cut down version of my original code
remotes:WaitForChild("HatchPet").OnServerEvent:Connect(function(plr, incubator)
if plr and incubator and incubator.Parent == workspace.Incubators then
local incubatorConfig = require(incubator.Configuration)
if plr.leaderstats.Coins.Value >= incubatorConfig.Price and #plr.PetsInventory:GetChildren() < config.MaxPetsInventory then
plr.leaderstats.Coins.Value -= incubatorConfig.Price
local chances = incubatorConfig.Chances
local plrChance = rnd:NextNumber() * 100
local n = 0
local rarityChosen = nil
for rarity, chance in pairs(chances) do
n += chance
if plrChance <= n then
rarityChosen = rarity
break
end
end
local hatchablePets = incubatorConfig.HatchablePets
print(hatchablePets)
for i = #hatchablePets, 2, -1 do
local j = rnd:NextInteger(1, i)
hatchablePets[i], hatchablePets[j] = hatchablePets[j], hatchablePets[i]
end
local petChosen
for _, petName in pairs(hatchablePets) do
if pets:FindFirstChild(petName, true) and pets:FindFirstChild(petName, true).Parent.Name == rarityChosen and pets:FindFirstChild(petName, true) ~= nil then
petChosen = petName
break
end
end
if petChosen ~= nil then
add(plr, petChosen)
end
print(petChosen)
remotes:WaitForChild("HatchPet"):FireClient(plr, petChosen)
end
end
end)