What is the :Disconnect() function primarily used for?

Hey, I’ve been coding for a while and I haven’t really heard of the :Disconnect() function at all, and I’ve never used it. I was just wondering what it was used for, because it might help me In the long run. My main guess is that it’s to disconnect a function from an event, but I’m not sure, which is why this topic was created.

26 Likes

You have just answered your own question. That is what it does.

Say for instance you have a part that kills a player. But you only want the part to kill one player. Disconnecting the Touched connection would come in handy:

local connection
connection = script.Parent.Touched:Connect(function(part)
    if part.Parent:FindFirstChild("Humanoid")
        part.Parent.Humanoid.Health = 0
        connection:Disconnect()
    end
end)
53 Likes

Just to add on, :Disconnect() is not needed if the event was connected to an object that has been destroyed, as any events connected to an object being removed will automatically be cleaned up.

18 Likes

Yeah I just wasn’t really sure. Thanks for the clarification!

1 Like

Yes this is correct. Instance:Destroy implicitly disconnects all connections.

7 Likes

You are right, it disconnects a function from an event, I believe this clears memory too

3 Likes

It is also used to prevent unused connection which causes game performance to decrease.

9 Likes

Oh yeah that could be helpful, thanks!

2 Likes

So I feel like I’m not reading this correctly, so I’m just going to clarify. When you said “one player” and it kills one player, it just completely stops waiting for that touched event?

1 Like

yeah thats basically what it does, just stops listening for the touched event.

2 Likes

hello just to add on you can use the Once method to make an event only trigger once instead of using Connection:Disconnect() for only 1 time

Example:

script.Parent.Touched:Once(function(part)
    if part.Parent:FindFirstChild("Humanoid")
        part.Parent.Humanoid.Health = 0
        connection:Disconnect()
    end
end)

The problem is that the function only runs once, so if the first part that triggers the event doesn’t have a parent with a Humanoid then your whole script will fall apart.

That’s why :Disconnect() is better here so that it keeps looking for a part that meets all the conditions instead of using :Once()