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

How to disconnect an event connection

How to disconnect an event connection

Jun 23 2018, 10:15 AM PST

Problem

You want to disconnect a connection.

Solution

Use the disconnect method of the Connection object.

local connection
connection = Workspace.Part.Touched:connect(function(hit)
	print(hit)
	connection:disconnect()
end)

Discussion

It’s quite beneficial to understand how an event connection works. So first we have the Event itself. An Event is a member of an object used to identify an occasion. An event is only used so that we can do something when it occurs. To do so, so we have to “connect” a callback to the event. We call this the callback a “listener” or “event handler.” Now notice that connect is just like any other method. It’s just a function so it can return a value. What it returns is a special Connection object.

In our example, we first define the variable “connection” because inside of its definition we’re going to be using it. We set “connection” to be the Connection object when we connect the Touched event to a callback. This callback prints what hit it and disconnects the event. This results in the connection firing, the object that touched Workspace.Part to be printed and the connection to be disconnected.

Tags:
  • event
  • touched