Debounce Troubles

Basically Im making an obby for practice, and at the end there is a trophy that once touched, sends you back to the beginning and gives you a win and restarts your checkpoints. However no matter where I put the waits it seems to give the player way too many wins

here’s my code. Also Ik its messy Im going to make it nicer and better later.

The touched event triggers multiple times when you touch the trophy. You need a debounce.

Yes I already know that but I have no idea how to Implement it

You should define a debounce variable and set it to false. Then in the touched event you can check if its false, and if it is, set it to true and teleport the player and give them their win. After a little wait, make it false again.

1 Like

As @argubarguilija222 mentioned, you would need to introduce a debounce in conjunction with the wait to prevent players from receiving more wins than intended.

Here’s an example revision of the code you posted to include a debounce:

Example Revision

local Players = game:GetService("Players")

local Trophy = workspace.Trophy
local Spawn = workspace.SpawnLocation
local Door = workspace.Entrance.Door
local MovingWall2 = workspace["Moving Wall2"]
local MovingWall3 = workspace["Moving Wall3"]

local Debounce = false
local Cooldown = 5

Trophy.Touched:Connect(function(hit)
    if Debounce ~= false then return end -- If debounce is not equal to false when the function runs, immediately stop the function.
    Debounce = true -- If it is false, set this to true so the code below cannot run again until it's set back to false.

    local Model = hit:FindFirstAncestorOfClass("Model")
    local player = Players:GetPlayerFromCharacter(Model)

    if Model and player then

        local leaderstats = player:FindFirstChild("leaderstats")
        if leaderstats then

            local Stage = leaderstats:FindFirstChild("Stage")
            local Wins = leaderstats:FindFirstChild("Wins")

            if Stage and Wins then
                Model:PivotTo(Vector3.new(-2, 1.5, -30.5))
                Spawn.Position = Vector3.new(-2, 1.5, -30.5)
                Door.Position = Vector3.new(21.5, 5, 40.5)
                MovingWall2.Position = Vector3.new(286.071, -4.929, 39.5)
                MovingWall3.Position = Vector3.new(277.5, 33.929, 909.929)

                Stage.Value = 1
                Wins.Value += 1
                task.wait(Cooldown)
            end
        end
    end

    Debounce = false -- Sets debounce back to false when the function's code has finished. This means that it's guaranteed that it has waited for the defined cooldown time (if the conditions necessary to reach that part of the function were true, at least)
end)
1 Like

Thank you for helping with the debounce

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.