Disconnecting Functions After Player Deaths

I’m trying to create a script where the player can change between accessories when they select an object on their screen. It works perfectly fine the first time and before the player dies, but once the player dies, the script does not work until the player resets to get their new accessory. I believe the issue is that the function within this won’t disconnect after a player dies, but I’m not entirely sure if that’s the issue and if it is, how to fix it.

game.Players.PlayerAdded:Connect(function(player)
player.CharacterAdded:Connect(function(character)
	local currentHat = player:WaitForChild("currentHat")
	local clone = script:FindFirstChild(currentHat.Value):Clone()
	clone.Parent = character
	clone.Handle.BrickColor = character.Head.BrickColor
	character.Head:GetPropertyChangedSignal("BrickColor"):Connect(function()
		clone.Handle.BrickColor = character["Body Colors"].HeadColor
	end)
	
	local arrowClone = script.ArrowStartPoint:Clone()
	arrowClone.Parent = character
	local cn = currentHat:GetPropertyChangedSignal("Value"):Connect(function()
		if player.Character then
			for i,v in pairs(player.Character:GetChildren()) do
				if v.Name == "ClownNose" or v.Name == "GruNose" or v.Name == "SharkNose" or v.Name == "SquidwardNose" or v.Name == "MrKrabs" or v.Name == "PigNose" or v.Name == "PinocchioNose" or v.Name == "RhinoNose" or v.Name == "NoseMesh" then
					v:Destroy()
					print("current hat value = "..currentHat.Value)
				end
			end
			local clone = script:FindFirstChild(currentHat.Value):Clone()
			clone.Parent = character
			clone.Handle.BrickColor = character.Head.BrickColor
			character.Head:GetPropertyChangedSignal("BrickColor"):Connect(function()
				clone.Handle.BrickColor = character["Body Colors"].HeadColor
			end)
		end
	end)
	character:WaitForChild("Humanoid").Died:Connect(function()
		cn:Disconnect()
	end)
end)

Any help is appreciated. Also, you can see my attempt to fix it within the script.

3 Likes

Maybe add something in so if the players health equals zero, the script is still true??
like
if player.health == 0 do

1 Like

Died is a better option when checking if a player’s dead, vs using an if statement every time a player’s health changed.

@OP I see you’re using an object called currentHat; is its value being changed by a LocalScript or Script?

You are waiting for the humanoid, if the humanoid is dead already then this won’t fire. Try this instead:

local humanoid = character:FindFirstChild("Humanoid")
if humanoid then
    humanoid.Died:Connect(function()
        cn:Disconnect()
    end)
end

If not, then try this, idk lol:

pcall(function()
    character.Humanoid.Died:Connect(function()
        cn:Disconnect()
    end)
end)
1 Like

CharacterAdded fires the moment the character is added. Unless they have another function connected to this event that destroys the humanoid, I really can’t see what would cause that situation.