Question with disconnecting events

Hello! I am currently trying to clean up when the round ends, and I have a for loop that loops through each tagged object and gives them both an touched event and touch ended event. My question is, how do I disconnect them? There are more then one so is it even possible to do this

for i, v in pairs(bla bla) do
local event = obj.Touched:Connect(function()

end)
end

Will that disconnect only one since that variable keeps getting set to something new?
How do I do this? I assumed a table but wasn’t sure how this would be done.

1 Like

Ive seen this done one of two ways, either disconnecting through the variable *1 or disconnecting from the access route to the object *2

*1 - event:Disconnect()

*2 - obj.Touched:Disconnect()

Either way should work.

If you are doing stuff like that personally id keep an array with all the connectons in (this makes it easy to find connection and remove them)

1 Like

I see! I haven’t disconnected events much and didn’t know about the second one I should definitely do it more!

local part = script.Parent

part.Touched:Connect(function(hit)
	print(hit.Name)
end)

task.wait(5)

part.Touched:Disconnect()

This would error, you need to do the former (assign the event connection object to a variable and then later call the instance method “:Disconnect()” on the connection object in order to disconnect the event).

A subtle difference between these two objects.

Here’s another example script with a few comments comprehensively explaining RBXScriptSignal and RBXScriptConnection objects.

local part = script.Parent

local signal = part.Touched --returns a RBXScriptSignal object which the instance methods ":Wait()" or ":Connect()" can be called on
local hit = signal:Wait() --yields the script until the event is fired, at which point its arguments are returned to the signal and this the variable
print(hit.Name) --prints name of touching part which caused event to fire
local connection = signal:Connect(function(hit) --returns a RBXScriptConnection object which has a ".Connected" property which can be indexed and an instance method ":Disconnect()" which can be called on it
	print(hit.Name) --prints name of touching part which caused event to fire
end)
print(connection.Connected) --prints true as the event is still connected
connection:Disconnect() --disconnects the RBXScriptConnection object
print(connection.Connected) --prints false as the event is no longer connected
3 Likes