Debounces

Debounces add cooldowns to functions to prevent scripts from breaking.

by spunargar

Author Avatar

Debounces are cooldowns that are used to prevent functions from overflowing. Today, we're gonna learn how to use them.

Let's say there's a Part that kills you when you touch it. It also changes color upon touching it. But we don't want players to die from touching it too much, as it gets annoying. So, we'll add a debounce to a Script within our block to prevent that. BUT first, we'll need the foundation of the script.

Kill function

function onTouched(hit)
    if hit.Parent:FindFirstChildOfClass("Humanoid")~=nil then
        hit.Parent:BreakJoints() -- oof
    end
end

That's the kill function, as you can see once you touch the part your joints will break (oof). But this isn't a kill brick tutorial, so let's move on.

Declaring our debounce

local canKill = true

function onTouched(hit)
    if hit.Parent:FindFirstChildOfClass("Humanoid")~=nil then
        hit.Parent:BreakJoints() -- oof
    end
end

The canKill variable is our debounce. So, when the part is touched, canKill is rendered false and cannot kill a player for a few seconds. We'll edit the onTouched function so that it has a cooldown.

Utilizing our debounce

local canKill = true

function onTouched(hit)
    if not canKill then
        return
    else
        if hit.Parent:FindFirstChildOfClass("Humanoid")~=nil then
            canKill = false
            hit.Parent:BreakJoints() -- oof
            wait(1)
            canKill = true
        end
    end
end

Conclusion

If canKill is false, the function returns until canKill is true again.

If the part detects a Humanoid, canKill is false for a second, and the player's no longer has the privilege to keep their joints. After said second, canKill reactivates and another player can die on impact.

So, here's our finished script:

local canKill = true

function onTouched(hit)
    if not canKill then
        return
    else
        if hit.Parent:FindFirstChildOfClass("Humanoid")~=nil then
            canKill = false
            hit.Parent:BreakJoints() -- oof
            wait(1)
            canKill = true
        end
    end
end

workspace.Part.Touched:Connect(onTouched)

Thanks for reading.

View in-game to comment, award, and more!