Connecting events when Character is added, disconnect the events when character is destroyed

For example, in a local script in PlayerScripts

Player.CharacterAdded:Connect(function(character)
    RunService.Heartbeat:Connect(function()
        print("idk")
    end)
end)

How do I disconnect the Heartbeat connection whenever the character is destoyed?

local heartBeatConnection

Player.CharacterAdded:Connect(function(character)
    heartBeatConnection = RunService.Heartbeat:Connect(function()
        print("idk")
    end)
end)

Player.CharacterRemoving:Connect(function()
    if heartBeatConnection then
        heartBeatConnection:Disconnect()
        heartBeatConnection = nil
    end
end)

Edits: fixed typos

Something like this.

1 Like

I would check if the humanoid died instead

It’s really no different. But it depends on what he is using this for, if the connection needs to be disconnected on death, then yeah, but if it needs to be disconnected and reconnected on respawn, the code I provided works best.

1 Like

True, but I wouldn’t do either method on the client side, as you can simply connect it forever (keep a reference to it if you wanna disconnect it later, and check if the player’s character is there or not (it will probably be there since it isn’t destroyed on death) and it is very quickly destroyed and recreated when the respawn sequence occurs.

Though my opinion is irrelevant as you already provided OP with a solution

Thought that there would be a simpler way than having to create a variable for the connection. I guess I’ll go on with this. Thanks.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.