Search code examples
roblox

How do I script my ROBLOX ClickDetector only allow click input once, so the script only plays once and cannot be spammed?


Please help me edit my script to make it so when the block/part is clicked it will only execute the script once? I don't want to be able to click the block/part multiple times and the script play out per click. It should only move as far as it's stated ONCE when the block/part is clicked.

My script:

enter image description here


Solution

  • A simple way of dealing with this is to set a boolean from false to true when it has been clicked once, and check at the top of the function whether that boolean is true or false before proceeding.

    local debounce = false
    function foo()
       if not debounce then
          debounce = true
          print("Hi!")
       end
    end
    
    foo() -- Will print "Hi!"
    foo() -- Will not print anything
    

    You can apply the same logic to your script. If you are certain you only want this to happen once, you can alternatively disconnect your OnServerEvent-event once it runs. An event connection can be stored as a variable and later :Disconnect()-ed, similar to how you :Connect().

    local myConnection
    myConnection = myEvent:Connect(function()
       myConnection:Disconnect()
       print("Hello!")
    end)
    myEvent:Fire() -- Prints "Hello!"
    myEvent:Fire() -- Does nothing, because it is no longer connected/listening for input.