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?
✓ ANSWER ACCEPTED
How do I make a onTouched:Connect function run only once?
2 answers
✓ Accepted answer
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)
1 comment
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!
function onTouched(hit)
-- code
connection:Disconnect()
end
local connection = script.Parent.Touched:Connect(onTouched)
or
script.Parent.Touched:Wait()
-- code
This discussion is preserved as it was. New answers, comments, and votes are closed.

2 comments
add a debounce and change it to true below the touched function
it is cause you have debounce off, turn it on in the touched function