How to get the new character when the player dies from client

I keep getting an infinite yield on my HumanoidRootPart. This is inside a UI, and I don’t want ResetOnSpawn set to true, as it takes a while for the UI to load all elements, and so would have to reload all the elements again after death (I left all that out of the code below)

return function()
	local Character = Player.Character or Player.CharacterAdded:Wait()
	local HumanoidRootPart = Character:WaitForChild('HumanoidRootPart')

    -- New character
	local function NewCharacter()
		Character = Player.Character or Player.CharacterAdded:Wait()
		HumanoidRootPart = Character:WaitForChild('HumanoidRootPart') -- Infinite yield
	end

    Character.Humanoid.Died:Connect(NewCharacter)
end

You could bind to the CharacterAdded function of the player.

Fired when a player’s character spawns or respawns.

Since it is fired whenever the player spawns / respawns and supplies the new character as an argument to the connected function, it should work.
image


Perhaps the code would look something like this:

return function()
    local Character = Player.Character or Player.CharacterAdded:Wait()
    local HumanoidRootPart = Character:WaitForChild('HumanoidRootPart')
    
    Player.CharacterAdded:Connect(function(character)
        HumanoidRootPart = character.PrimaryPart or character:WaitForChild("HumanoidRootPart")
    end)
end
3 Likes