Roblox objects and events, lesson 25
Debounce
Goal: Stop one touch from counting many times.
about 6 min3 practice exercises
Touched does not fire once. A character walking over a coin touches it with several parts, many times in a fraction of a second. Without protection, one coin can pay out ten times.
The fix is a debounce: a variable that remembers the coin is already being handled.
local Players = game:GetService("Players")
local coin = script.Parent
local collected = false
coin.Touched:Connect(function(hit)
if collected then
return
end
local player = Players:GetPlayerFromCharacter(hit.Parent)
if not player then
return
end
collected = true
print(player.Name .. " collected a coin")
coin.Transparency = 1
coin.CanCollide = false
task.wait(5)
coin.Transparency = 0
coin.CanCollide = true
collected = false
end)
The first touch from a player sets collected to true. Every touch after that hits the first guard and leaves. Five seconds later the coin comes back and the flag is reset.
The order matters. collected = true is set before the wait, so nothing can slip in while the coin is hidden.
The same pattern gives you cooldowns for buttons, abilities and anything else a player could spam.
Try it in Studio
Optional, and the best way to make it stick.
Remove the debounce from the lesson's coin script, add a print, and count how many times one walk over the coin prints.
Sources
Checked against Roblox's documentation on . The lesson is in our own words; these pages are the source of truth.