Script Stops Monitoring Player Death

This script checks if a player is dead or alive. For some reason, it stops running the second function (dead) but continuous to run the first function (alive). Can someone explain the reason for this? Thank you!

local player = game.Players.LocalPlayer
local character = player.Character

if not character or not character.Parent then
character = player.CharacterAdded:wait()
end

player.CharacterAdded:Connect(function()
print('alive')
player.PlayerScripts:FindFirstChild('ClickDetection').Disabled = false
end)

character:WaitForChild("Humanoid").Died:Connect(function()
print('died')
player.PlayerScripts:FindFirstChild('ClickDetection').Disabled = true

end)

image

When the character dies, the character model is destroyed together with all of it’s children. Thus the connection character.Humanoid.Died is automatically destroyed too because the Humanoid doesn’t exist anymore.

If you want to listen to deaths and respawns you should do this instead:

--On a Script

PlayersService.PlayerAdded:Connect(function(Player)
    --Code for when the player joins
    Player.CharacterAdded:Connect(function(Character)
        --Code for when the character is added
        Character:WaitForChild("Humanoid").Died:Connect(function()
            --code for when the humanoid dies
        end)
    end)
end
2 Likes
local player = game.Players.LocalPlayer
local character = player.Character or player.CharacterAdded:Wait()
local humanoid = character:WaitForChild("Humanoid")

humanoid.StateChanged:Connect(function(oldState, newState)
	if newState == Enum.HumanoidStateType.Dead then
		print('died')
		player.PlayerScripts:FindFirstChild('ClickDetection').Disabled = true
	else
		print('alive')
		player.PlayerScripts:FindFirstChild('ClickDetection').Disabled = false
	end
end)
1 Like

PlayerAdded doesn’t fire in local scripts because the local player instance already exists when the local script begins execution.

1 Like

Your problem is that you’re not resetting humanoid every time you die.

Here’s a fix:

local player = game.Players.LocalPlayer
local character = player.Character or player.CharacterAdded:Wait()
local humanoid = character:WaitForChild("Humanoid")

player.CharacterAdded:Connect(function()
	
	print('alive')
	character = player.Character
	
	humanoid = character:WaitForChild("Humanoid")
	
	humanoid.Died:Connect(function()
		print('died')
		player.PlayerScripts:FindFirstChild('ClickDetection').Disabled = true
	end)
	
	player.PlayerScripts:FindFirstChild('ClickDetection').Disabled = false
	
end)
1 Like