How do I use :Disconnect?

Hello, I was wondering, how can I use :Disconnect(), and if it can be used within a table, thanks for any answer.

When you make a connection to a function, that can be set as a variable like this:

local connection = example.Event:Connect(function() end)

You can disconnect the connection variable directly like so:

connection:Disconnect()

You can even disconnect the function from itself like this if you don’t localize the variable:

connection = example.Event:Connect(function()
    connection:Disconnect()
    print("hey") -- will still run
end)

I am not sure what you mean by used within any table, it gives me an impression you want to disconnect the table or something.

1 Like

You can store the variable assigned to the event within a table.

EG:

local Table = {}
Table["Connection"] = Instance.Event:Connect(function()
     Table["Connection"]:Disconnect()
end)

Never really done this before, but It should work.

Not sure if this is what you needed, but hope it helps!

1 Like

You should localize your variable, like so:

local connection
connection = example.Event:Connect(function()
    connection:Disconnect()
    print("hey") -- will NOT run
end)

And the print command will not run.

The print will run, if I recall correctly. Disconnect() just makes the connection stop listening for the event firing, not completely stop the function it connected.

3 Likes

Also, so , a connection must be always a function, right>?

A connection must always be linked to an event, not a function.

The event (also known as a RBXScriptSignal) is the thing which triggers the function. The event constantly is listening / checking for something to happen.

When you disconnect that event, it stops checking (also known as listening). So it will no longer be able to call the function you assigned to that event.

If I have a function I want to execute when someone touches a block, I can set up a Touched event. That touched event is constantly checking whether I’ve touched the block and will execute my function when triggered.

If I disconnect the event, it will no longer be checking if I am touching the brick. So there’s no way it will call my function anymore.

Real life analogy:

Imagine the event is a Ring doorbell button press. The function is the ding dong noise which plays when you press it.

If my doorbell runs out of battery, or I turn it off manually, it cannot detect whether I have pressed the doorbell.

So there’s no way the speaker (function) will play the ding dong because now the doorbell (event) isn’t even checking if someone’s pressed the bell… When you Disconnect an event listener, you prevent your function from being called by the event because it’s no longer checking to see if the event happened.

21 Likes