Is this the proper way to reconnect event listeners?

I have this code in one of my scripts, but the way I reconnect an event listener seems kind of strange. Is this the right way to handle connections?

local Players_Service = game:GetService("Players")

local Player = Players_Service.LocalPlayer
local Character = Player.Character or Player.CharacterAdded:Wait()
local Humanoid = Character:WaitForChild("Humanoid")

local HumanoidRunning_Connection = Humanoid.Running:Connect(function(WalkSpeed)
    --does something
end)

Player.CharacterAdded:Connect(function(CharacterAdded)
    Character = CharacterAdded
    Humanoid = Character:WaitForChild("Humanoid")
    HumanoidRunning_Connection:Disconnect()
    HumanoidRunning_Connection = Humanoid.Running:Connect(function(WalkSpeed)
        --does the same thing
    end)
end)

Note:
The code works fine, but my concern is the way I handle connections.

Instead of pasting the same code inside each connection, pass a function itself.

To do this, you just declare a function in the regular outer scope, and inside the :Connect(), use the function name.

For example:
function HandleWalkspeed()
—Code here.
end

Player.CharacterAdded:Connect(HandleWalkspeed)

3 Likes

You shouldn’t need to disconnect as the instance your original connection is hooked to gets destroyed(?) when the character is removed.

I need not disconnect the initial connection? So I am fine by just reconnecting the connection to the newly added humanoid?

Yes as far as I know, everything is cleaned up according to this https://developer.roblox.com/api-reference/function/Instance/Destroy

1 Like