Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
1

How do I make a onTouched:Connect function run only once?

Asked by 6 years ago

So I have ascript.Parent.Touched:Connect(function(hit) function that makes a block fade in, but it keeps on running even if it's in the middle of running. I want it to only run once and then keep the block visible. How would I do this?

0
add a debounce and change it to true below the touched function oSyM8V3N 429 — 6y
0
it is cause you have debounce off, turn it on in the touched function CrimsonFlux 6 — 6y

2 answers

Log in to vote
0
Answered by
Mayk728 855 Moderation Voter
6 years ago
Edited 6 years ago

Debounce! Debounce doesn't allow a function to run again until a set time has passed.

My example of Debounce;

local Part = script.Parent
local Debounce = false

Part.Touched:Connect(function(hit)
    if Debounce == false then
        Debounce = true
        print("This cannot run again until 5 seconds have passed!")
        wait(5)
        Debounce = false
    end
end)

If you want it to run only ONCE, then use connections and disconnect them.

local Part = script.Parent
local Connection

Connection = Part.Touched:Connect(function(hit)
    --Code
    Connection:Disconnect()
end)
0
Thank you! This worked well except for Connection:Disconnect being at the end of the script, as the script already picked up multiple connections before that, I simply moved it to the start of the script and it worked flawlessly! TiredMelon 405 — 6y
Ad
Log in to vote
0
Answered by
UgOsMiLy 1074 Moderation Voter
6 years ago
function onTouched(hit)
    -- code
    connection:Disconnect()
end

local connection = script.Parent.Touched:Connect(onTouched)

or

script.Parent.Touched:Wait()
-- code

Answer this question