Hello.
So I am trying to make a system where a player can punch once per a given amount of time. So I tried implementing a debounce into my script but for some reason it produces this:
My script is here:
local clickDetector = script.Parent.ClickDetector
local tree = script.Parent
local debounce = false
clickDetector.MouseClick:Connect(function(plr) --Detect when someone clicks the tree
local RightAnimation = plr.Character.Humanoid:LoadAnimation(script.Parent.RightPunch)
if not debounce then
RightAnimation:Play()
tree.Health.Value -= 1
script.Parent.BillboardGui.TextLabel.Text = tree.Health.Value.."/50"
if tree.Health.Value == 0 then tree:Destroy() end
debounce = true
else
wait(1)
debounce = false
end
end)
Your method of adding a debounce is wrong.
You must use the wait()
function along with the part to set the debounce back to true at the correct scope. You used it in a if and else statement scope which is wrong. Instead, you put them under the function’s scope and not any one of the inner scopes.
Like this?
local clickDetector = script.Parent.ClickDetector
local tree = script.Parent
local debounce = true
clickDetector.MouseClick:Connect(function(plr) --Detect when someone clicks the tree
local RightAnimation = plr.Character.Humanoid:LoadAnimation(script.Parent.RightPunch)
RightAnimation:Play()
tree.Health.Value -= 1 --IntValue rep
script.Parent.BillboardGui.TextLabel.Text = tree.Health.Value.."/50"
if tree.Health.Value == 0 then tree:Destroy() end --Check if the talueree has no health left then destroy if it doesresenting health
wait(0.5)
debounce = false
end)
1 Like
Well I tried and it only lets me punch once than just doesnt work
Wrong, make sure to check your debounce is true, if it is, right after the if statement set it to false.
Then once you done with your main code, wait for a certain amount of seconds and finally set the debounce back to true.
like this:
local clickDetector = script.Parent.ClickDetector
local tree = script.Parent
local debounce = true
clickDetector.MouseClick:Connect(function(plr) -- Detect when someone clicks the tree
if debounce == true then
debounce = false
local RightAnimation = plr.Character.Humanoid:LoadAnimation(script.Parent.RightPunch)
RightAnimation:Play()
tree.Health.Value -= 1 --IntValue rep
script.Parent.BillboardGui.TextLabel.Text = tree.Health.Value.."/50"
if tree.Health.Value == 0 then tree:Destroy() end -- Check if the talueree has no health left then destroy if it doesresenting health
end
wait(0.5)
debounce = true
end)
Put this in the end of the if statement.