PcoWSkbVqDnWTu_dm2ix
We use cookies on this site to enhance your user experience

Disconnecting an Event Connection

Disconnecting an Event Connection

Jan 30 2019, 3:57 PM PST

Problem

You want to disconnect a connection.

Solution

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:Disconnect()
end
connection = part.Touched:Connect(onTouched)

Discussion

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.

Tags:
  • event
  • touched