Scripting health bar

Hi there, I’m helping a friend work on their games UI and I thought that it would be a good idea to script part of it (as far as I’m aware they don’t have a scripter right now), but I can’t figure out how to script a textlabel for the health:

Script:

local plr = game.Players.LocalPlayer
local character = game:FindFirstChild(plr.Character)

character.Humanoid.MaxHealth.Changed:Connect(function()
script.Parent.Text = character.Humanoid.Health .. "/" .. character.Humanoid.MaxHealth
end)

character.Humanoid.Health.Changed:Connect(function()
script.Parent.Text = character.Humanoid.Health .. "/" .. character.Humanoid.MaxHealth
end)

Here’s the file structure for information:

image

Output:

image

1 Like

Should look more like this:

local character = plr.Character
character.humanoid:GetPropertyChangedSignal("Health"):Connect(function()
script.Parent.Text = character.Humanoid.Health .. "/" .. character.Humanoid.MaxHealth
end)
1 Like

Still not working (sorry for the late response, my WiFi connection is glitching so much right now):

image

fyi this line
local character = game:FindFirstChild(plr.Character)
can be simplified to
local character = plr.Character or plr.CharacterAdded:Wait()

since the way you are using it right now, FindFirstChild may return character as nil

Did originally have it set to this, using CharacterAdded now (thank you!) and it still doesn’t seem to be making a difference unfortunately, plus zero errors in output

Edit: Removing the wait for that brings up this:

image

You need the CharacterAdded:Wait() because you want the script to wait for the character to fully load, else the humanoid will be nil.

For the health changed part you should use the way that @Emskipo suggested with character.Humanoid:GetPropertyChangedSignal("Health"):Connect(function()

I’m using both changes and nothing is happening.

local character = plr.Character or plr.CharacterAdded:Wait()

keep in the or

Also, might want to add a var for humanoid;

local humanoid = character:WaitForChild("Humanoid")

You probably have to update it at first as well, so I’d try adding this to the end:

script.Parent.Text = character.Humanoid.Health.."/"..character.Humanoid.MaxHealth

Since you access the humanoid so much, I’d also add a variable for it:

local Hum = character:FindFirstChildOfClass("Humanoid")
1 Like

Finally works, thank you @Emskipo, @ReincarnatedC and @Inconcludable.

1 Like