Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

How to add a cool down to a button?

I'm trying to make a locked door that when you touch the locked door it plays a sound and enables a GUI saying that its locked, the problem is that when you press it, it tends to spam the sound and GUI.

script.Parent.Touched:Connect(function(hit)
if hit.Parent:FindFirstChild("Humanoid")then
game.ReplicatedStorage.LockedDoor:FireClient(game.Players:GetPlayerFromCharacter(hit.Parent)) 
end
end)


^ The script that's in the door.

2 answers

Howdy!

In the scripting world, we call this "debounce". Don't ask me why, the Code Gods just made it like that. The definition used by this site is:

Debounce is a term that is often associated with the act of adding a cool-down time to a function so it doesn't get called rapidly. This can be especially helpful when used in conjunction with the Touched event of parts. Oftentimes, this is accomplished by setting a variable to true at the beginning of a function, and setting it to false again at the end. Then, at the very beginning of the function, if the variable is already true, then you use the 'return' keyword, effectively ending the function.

Before your function, add a variable called "debounce" and set it to false. Then when the function is ran, set the debounce as true with a wait time of three seconds (or whatever you want). It'll look something like what I have below.

local Debounce = false

script.Parent.Touched:Connect(function(hit)
if hit.Parent:FindFirstChild("Humanoid") and not Debounce then
Debounce = true
game.ReplicatedStorage.LockedDoor:FireClient(game.Players:GetPlayerFromCharacter(hit.Parent))
wait(3)
Debounce = false
end
end)

If this helped you out, consider accepting this answer for those sweet, sweet reputation points. If not, comment below and I (or someone else) will help you out.

Be sure to check out the Roblox API Documentation as well for additional reference.

2 comments

0

It still repeats the action a bunch of times with debounce,

0

Just posted my answer and didn’t know someone else had answered, sorry about that

I think you do this

local debounce = false

script.Parent.Touched:Connect(function(hit)
 hit.Parent:FindFirstChild(“Humanoid”) then
  if debounce == false then
   debounce = true game.ReplicatedStorage.LockedDoor:FireClient(game.Players:GetPlayerFromCharacter(hit.Parent))
   wait( insert amount of time before door makes sound plus GUI shows up again )
   debounce = false
  end
 end
end)

hopefully this was helpful and the correct answer

4 comments

0

Still didn't work

0

Maybe if you change the if not debounce then to if debounce == false then

0

I’ve edited it so you see how it would look

0

It breaks the door and there's a lot of red underlines

This discussion is preserved as it was. New answers, comments, and votes are closed.