How to have a GUI display the health as a number

Hello, I am trying to make a health GUI like the one in GMOD, and so far it works fine, but it stops working every time I respawn the character as it just stays at 0 forever

This is the code



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

local Frame = player.PlayerGui.Health.Frame
local Health = Frame.Health
local Title = Frame.Title

local humanoid = character:WaitForChild("Humanoid")

humanoid.HealthChanged:Connect(function(newhp)
	Health.Text = newhp
	
	if newhp <= 0 then
		Title.TextColor3 = Color3.fromRGB(236, 56, 39)
		Health.TextColor3 = Color3.fromRGB(236, 56, 39)
	else
		Health.TextColor3 = Color3.fromRGB(236, 229, 89)
		Title.TextColor3 = Color3.fromRGB(236, 229, 89)
	end
end)```

Where is the script located? It should probably be in StarterPlayerScripts

The script is currently in StarterCharacterScripts

I tried StarterPlayerScripts and it still doesn’t work, it stays at 0 when spawning in.

Local scripts should be in StarterPlayerScripts rather than StarterCharacterScripts. I also recommend adding this to your code and seeing if it fixes the issue.

This is your revised code:


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

local Frame = player.PlayerGui.Health.Frame
local Health = Frame.Health
local Title = Frame.Title

local humanoid = character:WaitForChild("Humanoid")

humanoid.HealthChanged:Connect(function(newhp)
	Health.Text = newhp
	
	if newhp <= 0 then
		Title.TextColor3 = Color3.fromRGB(236, 56, 39)
		Health.TextColor3 = Color3.fromRGB(236, 56, 39)
	else
		Health.TextColor3 = Color3.fromRGB(236, 229, 89)
		Title.TextColor3 = Color3.fromRGB(236, 229, 89)
	end
end)

player.CharacterAdded:Connect(function()
Health.Text = "100" -- Set this to default health upon respawn
Health.TextColor3 = Color3.fromRGB(236, 229, 89)
Title.TextColor3 = Color3.fromRGB(236, 229, 89)
end)
local character = player.Character or player.CharacterAdded

Should be player.CharacterAdded:Wait(), player.CharacterAdded is simply a RBXScriptSignal object (always truthy).

2 Likes