Menu
CoddyTech

Coin Collector

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

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

To let it happen again later, wait and reset it: task.wait(3) then used = false. The wait pauses only this function, so other touches keep arriving and are ignored while used is true.

value += 1 is short for value = value + 1, and CanTouch = false makes a part stop firing Touched until it is set back to true.

challenge icon

Challenge

Medium

The leaderstats and the Touched connections are ready, but press Play and walk through a coin: Coins jumps by more than 1.

Fix it and finish the coins:

  1. Each coin gives exactly 1 Coin per pickup (a debounce per coin).
  2. A collected coin hides: Transparency 1 and CanTouch false.
  3. 3 seconds later it comes back (Transparency 0, CanTouch true) and can be collected again.

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
quiz iconTest yourself

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

All lessons in Roblox Game Scripting

Practice on your own: Online Lua compiler