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 7 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 — 7y
0
it is cause you have debounce off, turn it on in the touched function CrimsonFlux 6 — 7y

2 answers

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

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

My example of Debounce;

01local Part = script.Parent
02local Debounce = false
03 
04Part.Touched:Connect(function(hit)
05    if Debounce == false then
06        Debounce = true
07        print("This cannot run again until 5 seconds have passed!")
08        wait(5)
09        Debounce = false
10    end
11end)

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

1local Part = script.Parent
2local Connection
3 
4Connection = Part.Touched:Connect(function(hit)
5    --Code
6    Connection:Disconnect()
7end)
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 — 7y
Ad
Log in to vote
0
Answered by
UgOsMiLy 1074 Moderation Voter
7 years ago
1function onTouched(hit)
2    -- code
3    connection:Disconnect()
4end
5 
6local connection = script.Parent.Touched:Connect(onTouched)

or

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

Answer this question