Menu
CoddyTech

Coin Collector

Part of the Roblox Game Scripting section of Coddy's Lua journey. Lesson 15 of 25.

The treasure pad set Coins to 100. A coin should add 1, and that brings a new problem.

Touched fires once for every body part that touches, so one step onto a coin can fire it several times. Add 1 point each time and a single coin gives several points.

The fix is a debounce: a variable that remembers "this already happened" and makes the code ignore the repeats:

local used = false
button.Touched:Connect(function(hit)
	if not used then
		used = true
		print("Pressed!")
	end
end)

not used is true while used is false, so only the first touch gets past if not used. a and b is true only when both are true: if player and not used then needs a player and an unused button.

When a loop connects many parts, make the variable inside the loop, so each part gets its own. value += 1 is short for value = value + 1.

challenge icon

Challenge

Medium

Make each coin give exactly 1 Coin: walking through one now gives several.

  1. Inside the for loop, before Connect, add local collected = false.
  2. Change the check to if player and not collected then.
  3. Make collected = true the first line inside it.

Press Play and walk through a coin: Coins goes up by exactly 1. Then Check.

Try it yourself

local Players = game:GetService("Players")
local coins = workspace.Coins

Players.PlayerAdded:Connect(function(player)
	local leaderstats = Instance.new("Folder")
	leaderstats.Name = "leaderstats"
	leaderstats.Parent = player

	local coinsValue = Instance.new("IntValue")
	coinsValue.Name = "Coins"
	coinsValue.Value = 0
	coinsValue.Parent = leaderstats
end)

for _, coin in coins:GetChildren() do
	coin.Touched:Connect(function(hit)
		local player = Players:GetPlayerFromCharacter(hit.Parent)
		if player then
			player.leaderstats.Coins.Value += 1
		end
	end)
end

All lessons in Roblox Game Scripting

Practice on your own: Online Lua compiler