✓ Accepted answer
When using a debounce, you must satisfy all four parts:
- Index a variable and set it to false (or true if you want but we'll focus on the former).
- Within the if-then statement, check for whether the variable is set to false. If it is, the code will continue to run. If not, the code will not execute further.
- Usually the next line after the if-then statement, change the variable to the opposite (in this case, we'll change it to true). This prevents the script to run the code again since the variable is no longer equal to false. Thus the if-then statement fails and the rest of the code will not run which is what we want. We want the code to run once and not multiple times.
- After the code has executed completely, we change the variable back to false.
In your script, we will implement this:
local debounce = false
script.Parent.Touched:Connect(function(hit)
if debounce == false then
debounce = true
local char = hit.Parent:FindFirstChild("Humanoid")
char.Health = char.Health - 50
end
debounce = false
end)
But, we're not finished yet. This still fails. We're going to implement a second debounce to ensure this only runs once and not multiple times:
local debounce = false
local i = 0
script.Parent.Touched:Connect(function(hit)
if debounce == false and i == 0 then
debounce = true
i = i + 1
local char = hit.Parent:FindFirstChild("Humanoid")
char.Health = char.Health - 50
end
debounce = false
i = 0
end)
1 comment
You can do 'if debounce then' (or 'if not debounce then') which will make it a bit easier and shorter to write than 'if debounce == false'