DEV Community

CyberMax
CyberMax

Posted on Originally published at cybermaxtools.com

How to make a pet hatching system in Roblox Studio (server-checked Luau)

Egg hatching looks like a UI feature, but almost all of it is server code: who pays, what they get and where it is stored. This is a complete small version you can paste into Studio: one config table, one server script, one button.

The short version

A pet hatching system has four parts: a table of eggs with a price and a weight for each pet, a server script that checks the player's coins, rolls the pet and stores it under a unique id, an equip function with a slot limit, and a button on the client that only asks the server to hatch. The client never decides the pet, the price or the inventory.

Set it up in Studio

  1. In ReplicatedStorage, add a ModuleScript named EggConfig and paste the first block.
  2. In ServerScriptService, add a Script named PetServer and paste the second block. It creates its own remotes.
  3. In StarterGui, add a ScreenGui with a TextButton; put a LocalScript inside the button and paste the third block.
  4. Press Play and click the button. You start with 500 test coins, enough for five hatches.
  5. Replace the test profile in onJoin with your saved player data, so pets and coins persist.

The code

ReplicatedStorage/EggConfig (ModuleScript)

-- ReplicatedStorage/EggConfig (ModuleScript): one table that the server rolls from and the client can show
local EggConfig = {
    Starter = {
        price = 100,
        pets = {
            { id = "Cat", weight = 50 },
            { id = "Dog", weight = 35 },
            { id = "Fox", weight = 12 },
            { id = "Dragon", weight = 3 },
        },
    },
}

return EggConfig
Enter fullscreen mode Exit fullscreen mode

ServerScriptService/PetServer (Script)

local Players = game:GetService("Players")
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local HttpService = game:GetService("HttpService")

local EggConfig = require(ReplicatedStorage:WaitForChild("EggConfig"))

local MAX_PETS = 50
local MAX_EQUIPPED = 3
local HATCH_COOLDOWN = 0.5

-- remotes are made by the server, so there is nothing to forget in Studio
local remotes = Instance.new("Folder")
remotes.Name = "PetRemotes"
local hatchRemote = Instance.new("RemoteFunction")
hatchRemote.Name = "Hatch"
hatchRemote.Parent = remotes
local equipRemote = Instance.new("RemoteFunction")
equipRemote.Name = "Equip"
equipRemote.Parent = remotes
local petsChanged = Instance.new("RemoteEvent")
petsChanged.Name = "PetsChanged"
petsChanged.Parent = remotes
remotes.Parent = ReplicatedStorage

local rng = Random.new()
local profiles = {} -- [player] = { coins = number, pets = { [uid] = { id = string, equipped = boolean } } }
local lastHatch = {} -- [player] = os.clock() of the last hatch

local function countPets(profile)
    local total, equipped = 0, 0
    for _, pet in profile.pets do
        total += 1
        if pet.equipped then
            equipped += 1
        end
    end
    return total, equipped
end

local function roll(egg)
    local total = 0
    for _, entry in egg.pets do
        total += entry.weight
    end
    local r = rng:NextNumber() * total
    for _, entry in egg.pets do
        r -= entry.weight
        if r < 0 then
            return entry.id
        end
    end
    return egg.pets[#egg.pets].id
end

local function onJoin(player)
    profiles[player] = { coins = 500, pets = {} } -- swap this line for your saved data
    petsChanged:FireClient(player, profiles[player].pets, profiles[player].coins)
end

Players.PlayerAdded:Connect(onJoin)
for _, player in Players:GetPlayers() do
    task.spawn(onJoin, player)
end

Players.PlayerRemoving:Connect(function(player)
    profiles[player] = nil
    lastHatch[player] = nil
end)

hatchRemote.OnServerInvoke = function(player, eggName)
    local profile = profiles[player]
    local egg = if type(eggName) == "string" then EggConfig[eggName] else nil
    if not profile or not egg then
        return false, "Unknown egg"
    end
    local now = os.clock()
    if lastHatch[player] and now - lastHatch[player] < HATCH_COOLDOWN then
        return false, "Too fast"
    end
    lastHatch[player] = now
    if countPets(profile) >= MAX_PETS then
        return false, "Inventory full"
    end
    if profile.coins < egg.price then
        return false, "Not enough coins"
    end

    -- charge and grant in one step, with no yield in between
    profile.coins -= egg.price
    local petId = roll(egg)
    local uid = HttpService:GenerateGUID(false)
    profile.pets[uid] = { id = petId, equipped = false }
    petsChanged:FireClient(player, profile.pets, profile.coins)
    return true, petId, uid
end

equipRemote.OnServerInvoke = function(player, uid, wantEquipped)
    local profile = profiles[player]
    local pet = if profile and type(uid) == "string" then profile.pets[uid] else nil
    if not pet then
        return false, "No such pet"
    end
    wantEquipped = wantEquipped == true
    if wantEquipped and not pet.equipped then
        local _, equipped = countPets(profile)
        if equipped >= MAX_EQUIPPED then
            return false, "All pet slots are in use"
        end
    end
    pet.equipped = wantEquipped
    petsChanged:FireClient(player, profile.pets, profile.coins)
    return true
end
Enter fullscreen mode Exit fullscreen mode

StarterGui/ScreenGui/TextButton/LocalScript

local ReplicatedStorage = game:GetService("ReplicatedStorage")

local remotes = ReplicatedStorage:WaitForChild("PetRemotes")
local hatch = remotes:WaitForChild("Hatch")
local petsChanged = remotes:WaitForChild("PetsChanged")

local button = script.Parent
local IDLE_TEXT = "Hatch (100 coins)"
local busy = false
button.Text = IDLE_TEXT

button.Activated:Connect(function()
    if busy then
        return
    end
    busy = true
    button.Text = "Hatching..."
    local ok, result = hatch:InvokeServer("Starter")
    button.Text = if ok then "You got a " .. result .. "!" else result
    task.wait(1.5)
    button.Text = IDLE_TEXT
    busy = false
end)

petsChanged.OnClientEvent:Connect(function(pets, coins)
    local count = 0
    for _ in pets do
        count += 1
    end
    print("Coins:", coins, "Pets owned:", count) -- draw your inventory grid from `pets` here
end)
Enter fullscreen mode Exit fullscreen mode

How the roll works

Each pet has a weight. The server adds the weights, picks a random number between zero and that total, and walks down the list subtracting each weight until the number goes below zero. A pet with weight 50 out of a total of 100 comes out half the time.

Because the chance is always weight divided by total, you can print the odds for players from the same table the server rolls from, and the two can never disagree.

Why every pet gets a unique id

A player can own three Cats. If the inventory were a list of names, "equip Cat" would be ambiguous and deleting one would be guesswork. Giving each hatched pet its own id (a GUID) means equip, delete, trade and fuse all point at one exact pet.

What the server checks on every hatch

A remote can be fired by an exploiter with any arguments, as fast as they like. So the hatch handler checks five things before it does anything:

  • the egg name is a string and exists in EggConfig
  • the player has a loaded profile
  • at least half a second has passed since the last hatch
  • the inventory is not full
  • the player can afford the egg

Showing the pet in the world

This tutorial stops at the data: what the player owns and what is equipped. To show equipped pets, clone a pet model for each equipped entry when PetsChanged fires and move it beside the character every frame. Keep that visual work on the client, and keep ownership on the server.

Good to know

  • The charge and the grant happen in the same server step, with nothing that yields between them. That is what stops a player who leaves mid-hatch from paying for nothing or getting a pet for free.
  • RemoteFunction:InvokeServer waits for the answer, which is what a hatch button wants. Never call InvokeClient from the server: a client that does not answer would hang your script.

Questions

Where should the pets be saved?

With the rest of the player's data, as the same table this script keeps in profiles[player]: pets by unique id, with the pet name and an equipped flag. Save the pity counters there too if you add pity.

How do I add a second egg?

Add another entry to EggConfig with its own price and pets, and pass its name from the button. The server code does not change.

Can players cheat the odds?

Not if the roll runs on the server, as it does here. The client only sends the egg name and receives the result.

How many pets should a player be able to own?

Set MAX_PETS to what your inventory screen can show comfortably and what you are happy to save. Fifty to a few hundred is common; a cap also keeps a saved profile well inside the DataStore size limit.

If you would rather not write it

Start free: the free Hatchwren sampler: two real modules from the kit (Formation, which places pets around the player, and Signal) with the .rbxmx to drag into Studio. The full kit is on the same page. Hatchwren is this system finished and tested: eggs with shown odds, luck and pity, a triple hatch that charges once, auto-delete, a saved pet inventory with equip slots, Golden and Rainbow fusing, and pets that follow the player. Free sampler first, then the kit: https://cybermaxtools.com/roblox/kits/hatchwren/?utm_source=devto&utm_medium=article&utm_campaign=rbxtut-how-to-make-a-pet-hatching-system-in-rob

Roblox is a trademark of Roblox Corporation. CyberMax is not affiliated with or endorsed by Roblox.


Published automatically by CyberMax. Every number above comes from the linked public data; nothing is estimated.

Top comments (0)