Debounce in my script only working sometimes?

  1. What do you want to achieve? My goal is to make it so that way when a player walks over one part, it does something, and then when you walk over to the other part it does the opposite of the other part. For example when someone goes on the ice, skates appear on them but when they go off the ice their skates disappear.

  2. What is the issue? The scripts work fine without debounces (I do need them though to optimize the script) but when I add debounces to both of the parts, it only works for the first or second time.

  3. What solutions have you tried so far? I’ve tried numerous things but none of them seem to work. By the way, the script is registering the player hitting the part, it just doesn’t make it passed the if statement needed to run the rest of the code. Therefore, I concluded that the problem was with the debounce.

The script of the first part:

local Touched = false -- Debounce

script.Parent.Touched:Connect(function(hit)

    print("Player hit part") -- this always prints in the output whenever someone touched the part

    if not Touched then         

        Touched = true

        print("It made it inside an if statement")

        -- Code that I would do here

        wait(5) -- I tried it without a wait and it doesn't change anything

        print(Touched)

        Touched = false
    end
end)

Here is script two which is doing the opposite of script one:

local DoneTouching = false -- Debounce

script.Parent.Touched:Connect(function(hit)
    if not DoneTouching then

        DoneTouching = true

        if hit.Parent:FindFirstChild("Something", true) then
            -- Code in here
        end

        wait(3)

        DoneTouching = false
    end
end)

I have been stuck on trying to fix this for a while, so if there is a solution I would greatly appreciate it!

1 Like

Your issue is because the they are able to only get past the if statement every 5 seconds for the first one and 3 seconds for the second one.

Without the “Waits” it should not make much of a difference if the debounce stuff wasn’t there.

You could either lower the wait time or find a different approach to optimize them, like toggling between the two touched events.

1 Like

I’ve thought about making a boolvalue in the player that is switched to false when they first play, and then once they touch the part it switches to true. Then once they hit the other part it switches to false. So kind of like a debounce. Would this be worth doing?

2 Likes

It depends. I can see you wanting to use debounce as to not trigger the same code over and over in repeat. As long as the two parts that do so aren’t really close that the player could touch 1 then the other, yes I could see this being a good addtion.

2 Likes

Okay, thank you a lot! I tried it out and it seems that adding a boolvalue has solved the problem!