I made a toggle script, but I don’t want it to be spammed. I tried making a debounce but it won’t work. Here’s the code:
uis.InputBegan:Connect(function(input, processed)
if t.Parent.Parent == plr.Character and not reloading and equip_value == false then
if input.KeyCode ~= Enum.KeyCode.G or processed or reloading then return end
if toggle == false then
idle:Stop()
hold:Play()
print(“Toggle!”)
toggle = true
t.Parent.Events.Equip:FireServer()
else if toggle == true then
toggle = false
t.Parent.Events.Equip:FireServer()
idle:Play()
hold:Stop()
print(“Toggle off!”)
end
end
end
end)
Can you format it please? It’d make it a lot easier to read. However, from what I can see, you do not delay any time from switching the states of toggle. Try adding a wait before setting it back to a false state.
Surround your pasted code with ``` to format it this way.
-- here are the variables needed for the debounce functionality
local debounce = true
local cooldown = 1
-- indented the code and surrounded expressions with parentheses for easier reading
uis.InputBegan:Connect(function(input, processed)
-- no need to compare booleans to true or false, just use 'if (variable) then' or 'if (not variable) then'
-- also combined the if-statement after this to get rid of redundancy
if ((input.KeyCode == Enum.KeyCode.G) and (not processed)
and (t.Parent.Parent == plr.Character) and (not reloading)
and (not equip_value) and debounce) then
debounce = false
if (not toggle) then
idle:Stop()
hold:Play()
print(“Toggle!”)
toggle = true
t.Parent.Events.Equip:FireServer()
else -- you can just use 'else' since a boolean only has 2 possible values
toggle = false
t.Parent.Events.Equip:FireServer()
idle:Play()
hold:Stop()
print(“Toggle off!”)
end
-- add a delay so the event can be fired again after (cooldown) seconds
spawn(function()
wait(cooldown)
debounce = true
end)
end
end)
Try using the Stopped event for the animation before setting the debounce to false.
Example:
if toggle == false then
idle:Stop()
hold:Play()
hold.Stopped:Wait()
toggle = true
else
hold:Stop()
idle:Play()
idle.Stopped:Wait()
toggle = false
end
If you want the animation to stop playing before playing the other, use the IsPlaying property of the animation.
if toggle == false and idle.IsPlaying == false then --check if idle anim is playing before playing the hold anim
hold:Play()
--etc
elseif hold:IsPlaying == false then
idle:Play()
--etc
end
if t.Parent.Parent == plr.Character and not reloading and equip_value == false then
if input.KeyCode ~= Enum.KeyCode.G or processed or reloading then return end
if toggle == false and cd == false then
cd = true
idle:Stop()
hold:Play()
print("Toggle!")
toggle = true
t.Parent.Events.Equip:FireServer()
wait(1)
cd = false
else if toggle == true and cd == false then
toggle = false
cd = true
t.Parent.Events.Equip:FireServer()
idle:Play()
hold:Stop()
print("Toggle off!")
wait(1)
cd = false
end
end
end
end)```
I finally figured it out after just testing it around.