HealthChanged Error

I’m trying to make it so that the player’s health is displayed on the GUI. Now, a post like this has appeared several times on DevForum. My problem, however, is not that, it’s that I can’t find why I’m getting an error with the Humanoid.HealthChanged event.

Trying to find the problem, I made a short script that prints the player’s health when it changes. Again, error.

Code:

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

local humanoid = character:FindFirstChildWhichIsA("Humanoid")

humanoid.HealthChanged:Connect(function(newHP)
	print(newHP)
end)

Error:

Players.dodo64bit.PlayerGui.HealthPart.ChangeHealth:6: attempt to index nil with ‘HealthChanged’

So, in the end, my question is;
Why does this happen and how can I prevent it?

This is happening because you are trying to find the humanoid before it is created. Try this code:

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

local humanoid = character:WaitForChild("Humanoid")

humanoid.HealthChanged:Connect(function(newHP)
	print(newHP)
end)

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.