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.

22 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)
44 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.

17 Likes

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

1 Like

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

6 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.

7 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