Menu
CoddyTech

Piles Come Back

Lesson 4 of 18 in Coddy's Roblox Game: Pet Simulator course.

Once every pile is broken the game runs out of coins. A broken pile should come back on its spot after Settings.RespawnTime seconds.

The pile has to remember its spot. A table keyed by the pile does that:

local pileSpot = {} -- each pile -> the spot it stands on
pileSpot[pile] = spot

task.delay(seconds, fn, ...) calls a function later, with arguments, without stopping anything now:

task.delay(Settings.RespawnTime, spawnPile, spot)

Take the pile out of the table when it breaks, so the table does not keep every pile that ever existed.

challenge icon

Challenge

Easy
  1. Near the top: local pileSpot = {}.
  2. In spawnPile, store pileSpot[pile] = spot.
  3. In hitPile, when the pile breaks: read its spot, remove it from pileSpot, destroy the pile, and task.delay(Settings.RespawnTime, spawnPile, spot).

This lesson's piles come back after 1 second. Press Play, then Check.

Try it yourself

local Players = game:GetService("Players")
local ServerStorage = game:GetService("ServerStorage")
local Settings = require(game.ReplicatedStorage.Settings)

local piles = workspace.Piles

print("A Meadow pile gives " .. Settings.PileValue .. " coins")

-- Every player gets Coins on the leaderboard
Players.PlayerAdded:Connect(function(player)
	local leaderstats = Instance.new("Folder")
	leaderstats.Name = "leaderstats"
	leaderstats.Parent = player

	local coins = Instance.new("IntValue")
	coins.Name = "Coins"
	coins.Parent = leaderstats
end)

-- A pile's click needs hitPile, which is written below spawnPile: name it
-- here, before either
local hitPile

-- A coin pile on a spot: a copy of ServerStorage.CoinPile with its health
-- and value as attributes
local function spawnPile(spot)
	local pile = ServerStorage.CoinPile:Clone()
	pile.Position = spot.Position
	pile:SetAttribute("MaxHealth", Settings.PileHealth)
	pile:SetAttribute("Health", Settings.PileHealth)
	pile:SetAttribute("Value", Settings.PileValue)
	-- click it to hit it
	local detector = Instance.new("ClickDetector")
	detector.Parent = pile
	pile.Parent = piles
	detector.MouseClick:Connect(function(player)
		hitPile(player, pile)
	end)
	return pile
end

-- A hit takes 1 off a pile's health;
-- at 0 the pile breaks and pays its value
function hitPile(player, pile)
	local health = pile:GetAttribute("Health") - 1
	if health > 0 then
		pile:SetAttribute("Health", health)
		return
	end
	player.leaderstats.Coins.Value += pile:GetAttribute("Value")
	pile:Destroy()
end

-- A pile on every spot in the Meadow
for _, spot in workspace.Zones.Meadow.Spawns:GetChildren() do
	spawnPile(spot)
end
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Roblox Game: Pet Simulator