I am making a lever for a cart ride game to switch tracks but I also want to implement cooldowns to prevent abuse. The code snippet below is responsible for this but nothing seems to be happening. No cooldown actually happens and it just lets you spam it.
lever.ClickDetector.MouseClick:Connect(function()
if pulled == false and debounce == false then
openleft()
elseif pulled == true and debounce == false then
openright()
end
pulled = not pulled
debounce = true
task.wait()
debounce = false
end)
Only the front of the script is dependent on the debounce. Wrap everything from ‘pulled = not pulled’ to ‘debounce = false’ in an ‘if debounce == false then’…
becuase task.wait() is empty which means that it will wait for only one frame
also note that the wait time will happen if the 2 if conditions failed to fix that add the debounce inside of their scope
this script should make it wait for 1 second
lever.ClickDetector.MouseClick:Connect(function()
if pulled == false and debounce == false then
openleft()
debounce = true
task.wait(1)
pulled = not pulled
debounce = false -- debounce
elseif pulled == true and debounce == false then
openright()
debounce = true
task.wait(1)
pulled = not pulled
debounce = false -- debounce
end
end)
GE_0E is right, the task.wait() is empty so it doesn’t wait at all because of no throttling, and you forgot to add a
if not debounce then
--code
end
it should work fine after that
Final code :
lever.ClickDetector.MouseClick:Connect(function()
if pulled == false and debounce == false then
openleft()
debounce = true
task.wait(1)
pulled = not pulled
debounce = false -- debounce
elseif pulled == true and debounce == false then
openright()
if debounce then return end
debounce = true
pulled = not pulled
task.wait(debounce duration)
debounce = false -- debounce
end
end)