Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

How can I disconnect an event from inside the function connected?

I have a Touched event connected to a simple function and I want to stop detecting it.

But it's a specific situation where I got to disconnect it from inside the function and (if I use the Disconnect() method) the variable is local, something like this:

local connection = part.Touched:connect(function()
	if condition then
		connection:Disconnect()
	end
end)

But it doesn't seem to work. Like this, it outputs the "attempt to index a nil value" error.

Is there something I could do to solve this? The event has to stop, because it will be assigned to a large number of parts, so I want to prevent unnecessary running code. And the connection has to be local because everything is inside a GetChildren() loop.

yikes

2 comments

0

Do you just mean ending the event/function? Because you could just do a return

0

Return would stop the function, right? I want to prevent it from running, the Touched can't happen.

2 answers

Add a one way debounce. That's all there's to it.

--blocks code execution
local debounce = false
local connection = part.Touched:connect(function()
	if condition and not debounce then
		debounce = true
		-- do stuff
	end
end)


--or

--removes event completely.
local connection 
connection = part.Touched:connect(function()
	if condition then
		-- do stuff
		connection = nil
	end
end)

1 comment

0

It doesn't disconnect the event, just blocks the rest of the code after being triggered.

To whom may concern, the solution brought by BlueTaslem was this:

local connection; connection = part.Touched:connect(function()
    if condition then
        connection:Disconnect()
    end
end)

1 comment

0

Too bad I can't accept 'my own' answer.

This discussion is preserved as it was. New answers, comments, and votes are closed.