Disconnecting character connections

I’m trying to optimize my game as much as possible, especially since fps drops to 52 when players’ respawns (why?) and I figured connections might a play role but I’m not sure to handle them properly.

local Players = game:GetService("Players")
local Connections = {}
Players.PlayerAdded:Connect(function(Player)
	Connections[Player.Name] = {}
	Player.CharacterAdded:Connect(function(Character) -- On PlayerRemoving do I also disconnect this?
		-- Connections relating to player
		table.insert(Connections[Player.Name], Character.Humanoid.Died:Connect(function()
			for _,v in Connections[Player.Name] do
				v:Disconnect()
			end
			table.clear(Connections[Player.Name])
		end))
	end)
end)

Or

local Players = game:GetService("Players")
local Connections = {}
Players.PlayerAdded:Connect(function(Player)
	Connections[Player.Name] = {}
	Player.CharacterAdded:Connect(function(Character)
		-- Connections relating to player
		table.insert(Connections[Player.Name], Character.Humanoid.Died:Connect(function()
			
			--
		end))
	end)
	Player.CharacterRemoving:Connect(function(Character) -- usually occurs on death, recommended to use character removing apparently?
		for _,v in Connections[Player.Name] do
			v:Disconnect()
		end
		Character:Destroy() -- Necessary or not?
		table.clear(Connections[Player.Name])
	end)
end)
Players.PlayerRemoving:Connect(function(Player)
	for _,v:RBXScriptConnection? in Connections[Player.Name] do
		pcall(function()
			v:Disconnect()
		end)
	end
	table.clear(Connections[Player.Name])
	Connections[Player.Name] = nil
end)

It states here that connections tied to an instance automatically disconnect when the instance is destroyed. This is true for the player instance as well (when they leave the game)

I figured same, but upon looking more, it turns out that connections still run, hence the huge fps drop (from 60 to 52) on respawn. and characters aren’t really destroyed properly.

Strange. Are you sure connections are causing the problem? I’m assuming that the code you provided is just a demonstration to get your point across and not the code you have implemented. Do you create or destroy anything whenever the character respawns?

Retracting my previous statement. It seems that the character doesn’t get destroyed when removed (as stated here) - so your initial assumption was correct. He provides a workaround for this which just includes setting the player’s character property to nil and then destroying the character.

1 Like

That was my initial plan, indeed. But I’m still confuzzled on which method I should use to clear connections.

Probably the second method where you use Player.CharacterRemoving instead of Character.Humanoid.Died. The player instance should properly get destroyed according to this official ROBLOX post, so you shouldn’t have to further worry about disconnecting connections tied to it.

1 Like