Disconnecting an Event Connection

Disconnecting an Event Connection

Mar 30 2021, 5:20 AM PST


You want to disconnect a connection.


Use the Disconnect method of the connection object returned by Connect.

local part = Workspace.Part
local connection
local function onTouched(otherPart)
	print("Touched by: " .. otherPart.Name)
connection = part.Touched:Connect(onTouched)


It’s quite beneficial to understand how an event connection works: an Event is a member of an object used to identify some occasion. To detect when an event occurs (or fires), so we must connect a function to it (using Connect). This function is called a “listener” or “event handler.” The Connect function returns an object called an RBXScriptConnection, or just connection for short. This connection object exists to serve one purpose - to disconnect the function we connected from the event.

In this example, we first define the local variable “connection” so that it can be used inside the function onTouched. We set the connection variable to be the value returned from Connect (the returned connection object). The onTouched function will print the object that touched the part, then immediately disconnect the function from the event by calling Disconnect on the connection object. This prevents future touches from calling onTouched.

  • event
  • touched