Local scripts in characters get reset when the character dies I think.
Also, The error was you get the character immediately. The character needs time to load in, plus, you should always use ServerScripts wherever possible. If for whatever reason you can’t, the CharacterAdded event is useful:
local Character = game:GetService("Players").LocalPlayer.Character or game:GetService("Players").LocalPlayer.CharacterAdded:Wait()
--when the character is added, you can use it as the character.
A humanoid is a class object, meaning you can retrieve it using the FindFirstChildOfClass function. I’d highly advise against using WaitForChild on a Humanoid, because it will most likely error from what I’ve expereinced.
local players = game:GetService("Players")
local player = players.LocalPlayer
local character = player.Character or player.CharacterAdded:Wait()
local humanoid = character:WaitForChild("Humanoid")
humanoid.Died:Connect(function()
print("Hello world!")
end)
You need to wait for the character to be added/loaded before attempting to index its “Humanoid” instance.
You’re right. You can use the CharacterAdded event to get the new Humanoid and make a new connection for that Humanoid’s Died event.
So, something like this:
local function onCharacterAdded(character)
local player = game:GetService("Players").LocalPlayer -- This is how you could get the player here
local humanoid = character:WaitForChild("Humanoid", 5)
if not humanoid then
return
end
humanoid.Died:Connect(function()
print("Player died!")
end)
end
game:GetService("Players").LocalPlayer.CharacterAdded:Connect(onCharacterAdded)
do -- Should do something like this for code that starts after the game does. In this case it's not needed because the character won't exist when the player joins/when LocalScripts start.
local alreadyExistingCharacter = game:GetService("Players").LocalPlayer.Character
if alreadyExistingCharacter then
onCharacterAdded(alreadyExistingCharacter )
end
end