Introduction
Hello! I’m Auiyin and I’ll be showing you guys how to add cooldowns in your scripts by using debounce.
What is Debounce
First of all, we have to know what debounce is. To put into simple terms, debounce is a type of variable that you switch from one value to another. (these are usually bool values)
How do I use Debounce?
To use debounce, all you have to do is create a variable and have it set to a value. Then you have an if statement that checks for the value of the variable, and temporarily set the variable to something else so that the script won’t run again until the variable is changed back to its original value.
Example of Debounce
For this example, I’ll be making a part that prints out “Hello” whenever it is stepped on with a cooldown of 1 second.
How your Explorer Should Look
local part = script.Parent
local debounce = false
part.Touched:Connect(function(hit)
if hit.Parent:FindFirstChild("Humanoid") then
if not debounce then
debounce = true
print("Hello world!")
wait(1)
debounce = false
end
end
end)
Explanation of Each Line
line 1: local part = script.Parent
creates a variable called part and sets the value to script.Parent
, basically means that every time we say part
in our script, it’s the same thing as saying script.Parent
.
line 2: local debounce = false
creates a variable called debounce and sets the value to false, works the same way above.
line 4: part.Touched:Connect(function(hit)
runs whatever is below it whenever the part is touched. The reason why we can’t just have this and remove the other part is because whenever a player steps onto a part, multiple limbs are touching the part which causes a bunch of signals to be sent to the script. This means that even if we stepped on the part “once”, it may think that we stepped on it multiple times.
line 5: if hit.Parent:FindFirstChild("Humanoid") then
is checking if a player touched the part, so we don’t get any random signals from other sources. (if you want parts to be able to activate the script, feel free to remove this)
line 6: if not debounce then
detects if our variable debounce is set to false, and if it is, then we run whatever is below it.
line 7: debounce = true
one of the more important lines as it prevents the if statement above from running again until changed.
line 8: print("Hello world!")
prints out Hello world! in the console so we can check how many times our script is being run.
line 9: wait(1)
waits 1 second before moving on, basically how long the cooldown is.
line 10: debounce = false
sets debounce back to false so the script can run again.
line 11: end
closes the if not debounce then
so the script knows where to stop.
line 12: end
closes the if hit.Parent:FindFirstChild("Humanoid") then
so the script knows where to stop.
line 13: end)
closes the part.Touched:Connect(function(hit)
so the script knows where to stop.
And that’s it! Now you should know how to create cooldowns by using debounce.