Egg system problem

Hi devs, im trying to do a simulator.

I have few problems on the pet system.

The problems are:

1)Template still there after cloning
2)Error in output(attempt to concatenate string with nil)
3)Error in output(pairsing problem)
4)Template not cloning in the other egg

When i try to buy the egg this happens(Basketball Egg):
image

When i try to buy an egg on the Rare basketball egg this happens:
image
Also in the Rare basketball egg there are no pets in the container.

These are the scripts:

Handler(local script(startergui))

local ReplicatedStorage = game:GetService("ReplicatedStorage")
local MarketPlaceService = game:GetService("MarketplaceService")
local UserInputService = game:GetService("UserInputService")
local Players = game:GetService("Players")

local Player = Players.LocalPlayer

local EggsFolder = workspace.Eggs
local PetModels = ReplicatedStorage:WaitForChild("Pets")
local EggConfig = require(ReplicatedStorage:WaitForChild("Config"):WaitForChild("EggsConfig"))
local BuyEgg = ReplicatedStorage:WaitForChild("Remotes"):WaitForChild("BuyEgg")
local PetHatched = ReplicatedStorage:WaitForChild("Remotes"):WaitForChild("PetHatched")

local template = script.Parent.Template


local function GetRarityColor(rarity: string)
	local color
	
	if rarity == "Common" then
		color = Color3.fromRGB(173, 173, 173)
	elseif rarity == "Uncommon" then
		color = Color3.fromRGB(9, 176, 0)
	elseif rarity == "Rare" then
		color = Color3.fromRGB(19, 193, 164)
	elseif rarity == "Secret" then
		color = Color3.fromRGB(0, 0, 0)
	end
	
	return color
end

local function GetRarity(rarity: string)
	local rarrity
	
	if rarity == "Common" then
		rarrity = "Common"
	elseif rarity == "Uncommon" then
		rarrity = "Uncommon"
	elseif rarity == "Rare" then
		rarrity = "Rare"
	elseif rarity == "Secret" then
		rarrity = "??"
	end
	
	return rarrity
end

local function generateViewportFrame(viewportFrame: ViewportFrame, petModel: Model)
	petModel:PivotTo(CFrame.new() * CFrame.Angles(0, math.rad(180), 0))
	petModel.Parent = viewportFrame
	
	local camera = Instance.new("Camera", viewportFrame)
	viewportFrame.CurrentCamera = camera
	
	camera.CFrame = CFrame.new(Vector3.new(-1,1,4), petModel.PrimaryPart.Position)
	if petModel.Name == "GiantDoge" or "GiantChicken" then
		camera.FieldOfView = 50
	else
		camera.FieldOfView = 30
	end
end

local function generatePet(container: Frame, petConfig: table)
	local clone = container.Template:Clone()
	clone.Parent = container
	clone.Name = petConfig.ID
	clone.Visible = true
	clone.PetName.Text = petConfig.ID:gsub("_", " ")
	clone.Rarity.Text = GetRarity(petConfig.Rarity) 
	clone.Rarity.TextColor3 = GetRarityColor(petConfig.Rarity)

	local petClone = PetModels[petConfig.ID]:Clone()
	generateViewportFrame(clone.ViewportFrame, petClone)
	
	clone.MouseEnter:Connect(function()
		if petConfig.Chance > 1 then
			clone.Rarity.Text = petConfig.Chance.."%"
		else
			clone.Rarity.Text = "??"
		end
	end)
	clone.MouseLeave:Connect(function()
		if petConfig.Rarity == "Secret" then
			clone.Rarity.Text = "??"
		elseif petConfig.Rarity ~= "Secret" then
			clone.Rarity.Text = petConfig.Rarity
		end
	end)
end

local function requestHatch(eggId: string, action: string)
	if action == "Auto" then
		--if not Player.gamepasses.Auto.Value then
		--prompt
		--else
		BuyEgg:fireServer(eggId, "Auto")
		--end
	elseif action == "x1" then
		BuyEgg:FireServer(eggId)
	elseif action == "x3" then
		--if not Player.gamepasses.Auto.Value then
		--prompt
		--else
		BuyEgg:FireServer(eggId, "x3")
		--end
	end
end

local function generateBillGui(eggModel: Instance, eggConfig: table)
	local attachment = eggModel.Attachment
	local clone = template:Clone()
	clone.Parent = script.Parent
	clone.Adornee = attachment
	clone.Name = eggModel.Name
	
	clone.Frame.Title.TextLabel.Text = eggModel.Name:gsub("_", " ")
	clone.Frame.Display.TextLabel.Text = eggConfig.Price
	
	for _, pet in ipairs(eggConfig.Pets) do
		generatePet(clone.Frame.Container, pet)
	end
	
	clone.Frame.BtnsHolder.Buy1.MouseButton1Click:Connect(function()
		BuyEgg:FireServer(eggModel.Name, "x1")
	end)
	
	clone.Frame.BtnsHolder.Buy3.MouseButton1Click:Connect(function()
		BuyEgg:fireServer(eggModel.Name, "x3")
	end)
	
	clone.Frame.BtnsHolder.AutoBuy.MouseButton1Click:Connect(function()
		BuyEgg:fireServer(eggModel.Name, "Auto")
	end)
end

for eggName, eggConfig in pairs(EggConfig) do
	generateBillGui(EggsFolder[eggName], eggConfig )
end

local function getClosestEgg()
	local closest = {Egg = nil, Distance = 9_999}
	
	for _, egg in ipairs(EggsFolder:GetChildren()) do
		local distanceBetween = (Player.Character.PrimaryPart.Position - egg.Position).Magnitude
		if distanceBetween > 17 then continue end
		
		if closest.Distance > distanceBetween then
			closest = {Egg = egg.Name, Distance = distanceBetween}
		end
	end
	
	return closest.Egg
end

UserInputService.InputEnded:Connect(function(input: InputObject, gameProcessedEvent: boolean)
	if gameProcessedEvent then return end
	if input.UserInputType ~= Enum.UserInputType.Keyboard then return end
	
	local eggId = getClosestEgg()
	if not eggId then return end
	
	if input.KeyCode == Enum.KeyCode.T then
		requestHatch(eggId, "Auto")
	elseif input.KeyCode == Enum.KeyCode.E then
		requestHatch(eggId, "x1")
	elseif input.KeyCode == Enum.KeyCode.R then
		requestHatch(eggId, "x3")
	end
end)

PetHatched.OnClientEvent:Connect(function(pet: table)
	print("You got a "..pet.Rarity.." "..pet.Name)
end)

Script that handles the buy(script(serverscriptservice))

local ReplicatedStorage = game:GetService("ReplicatedStorage")
local EggsFolder = workspace.Eggs

local EggsConfig = require(ReplicatedStorage:FindFirstChild("Config"):FindFirstChild("EggsConfig"))
local BuyEgg = ReplicatedStorage:WaitForChild("Remotes"):WaitForChild("BuyEgg")
local PetHatched = ReplicatedStorage:WaitForChild("Remotes"):WaitForChild("PetHatched")

local HATCH_COOLDOWN = 3

local HatchCooldown = {}

local function choosePet(pets: table)
	local totalWeight = 0
	
	for _, pet in ipairs(pets) do
		totalWeight += pet.Chance
	end
	
	local chance = math.random(1, totalWeight)
	local counter = 0
	for _, pet in ipairs(pets) do
		counter += pet.Chance
		if chance <= counter then
			return pet
		end
	end
end

local function hatch(player: Player, eggId: string)
	if HatchCooldown[player.UserId] then return end
	
	local eggConfig = EggsConfig[eggId]
	local playerBalance = player.leaderstats.Coins.Value
	
	if playerBalance < eggConfig.Price then return end
	HatchCooldown[player.UserId] = true
	
	player.leaderstats.Coins.Value -= eggConfig.Price
	
	local pet = choosePet(eggConfig.Pets)
	PetHatched:FireClient(player, pet)
	
	task.delay(HATCH_COOLDOWN, function()
		HatchCooldown[player.UserId] = nil
	end)
end

local function canHatch(player: Player, eggId: string)
	local eggConfig = EggsConfig[eggId]
	
	if not eggConfig then return false end
	
	local playerBalance = player.leaderstats.Coins.Value
	return playerBalance >= eggConfig.Price
end

BuyEgg.OnServerEvent:Connect(function(player: Player, eggId: string, action: string)
	if not canHatch(player, eggId) then return end
	
	if action == "Auto" then
		--
	elseif action == "x3" then
		--
	else
		hatch(player, eggId)
	end
end)

EggConfig(modulescript(rep.storage)

local module = {
	Basketball_Egg = {
		Price = 2_000,
		Pets = {
			{
				ID = "Dog", name = "Dog", Rarity = "Common", Chance = 30
			},
			{
				ID = "Cat", name = "Cat", Rarity = "Common", Chance = 25
			},
			{
				ID = "Seal", name = "Seal", Rarity = "Uncommon", Chance = 20
			},
			{
				ID = "Doge", name = "Doge", Rarity = "Uncommon", Chance = 15
			},
			{
				ID = "Chicken", name = "Chicken", Rarity = "Rare", Chance = 10
			},
			{
				ID = "GiantDoge", name = "Giant Doge", Rarity = "Secret", Chance = 0.001
			},
			{
				ID = "GiantChicken", name = "Giant Chicken", Rarity = "Secret", Chance = 0.001
			},
		}
	},
	Rare_Basketball_Egg = {
		Price = 5_000,
		Pets = {
			ID = "Pig", name = "Pig", Rarity = "Uncommon", Chance = 50
		},
		{
			ID = "Dog", name = "Dog", Rarity = "Uncommon", Chance = 50
		}
	}
}

return module

Thanks!

1 Like

One of these variables seem to be nil according to the error.

If the data is from the ModuleScript it should be:
print("You got a "..pet.Rarity.." "..pet.name)
pet.name is lowercase.

totalWeight seems to be nothing or not a number.
Try printing these variables.

1 Like

For the math.random() error, just use Random.new():NextInteger() or Random.new():NextNumber() because they dont have the interval problem

1 Like

Ok, i updated:
image

image

Thanks!

pet.name not pet.Name

Chars

3 Likes

Thanks bro, im so stupid i didnt realise that it was capital N… lol…

By the way, now, in the other egg, there are still no templates and wheni try to buy it says:
image

Also, the problem n.1 is fixed already

Some of the chances are lower than 1, so the interval error occurs.

Use Random.new():NextInteger() please, it will literally fix the problem

1 Like

how do i use it? im not that good at luau… i only know some basics… thanks!

image

local chance = Random.new():NextInteger(1,totalWeight)
1 Like

Now the output says this:

image

Thanks!

Can you show the line where it errors?

Yea, sure!
image

image
Script that fires

Ah, the first param you sent was the player, so the pet would be the second parameter

So, what do i need to do? Thanks!

Just do:

PetHatched.OnClientEvent:Connect(function(player,pet: table)
    print("You got a  " .. pet.Rarity .. " " .. pet.Name)
end)
1 Like