Menu
CoddyTech

Break a Pile

Lesson 3 of 18 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
  1. Above spawnPile, declare local hitPile.
  2. In spawnPile, add a ClickDetector to the pile and connect its MouseClick to hitPile(player, pile).
  3. Below spawnPile, write function hitPile(player, pile): take 1 off the Health attribute; if it is still above 0 store it and stop; otherwise add the pile's Value to the player's Coins and destroy the pile.

Press Play and click a pile three times. 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

-- 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