Menu
CoddyTech

Break a Pile

Lesson 3 of 20 in Coddy's Roblox Game: Pet Simulator course.

Players break piles by clicking them. A ClickDetector inside a part fires MouseClick on the server, with the player who clicked, when they are close enough.

Each click takes 1 off the pile's Health. When it reaches 0 the pile breaks: the player gets its Value in coins, and the pile is destroyed.

local health = pile:GetAttribute("Health") - 1
if health > 0 then
	pile:SetAttribute("Health", health)
	return
end
-- broken

The click is connected inside spawnPile, and it calls hitPile, which is written below spawnPile. A function can only use a local name that is already declared, so declare local hitPile first, above both, and fill it in later with function hitPile(player, pile).

challenge icon

Challenge

Easy

Break a pile by clicking it.

  1. Above spawnPile, declare local hitPile.
  2. In spawnPile, add a ClickDetector to the pile; its MouseClick calls hitPile(player, pile).
  3. Below, write function hitPile(player, pile): take 1 off Health; above 0, store it and stop; else add the pile's Value to Coins and destroy the pile.

Press Play and click a pile three times: it breaks and Coins goes up by 5. 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 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)
	pile.Parent = piles
	return pile
end

-- Lesson 3: Break a Pile goes here

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

All lessons in Roblox Game: Pet Simulator

Practice on your own: Roblox playground