Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

Why is my script not linking the text with the health? [SOLVED]

So i'm making a health bar gui for an NPC and it's meant to change the value of the health when it takes damage but it only works when the NPC dies. Any help?

local human = script.Parent.Parent.Parent.Parent.Humanoid
while true do
wait()
script.Parent.Text = human.Health
end

1 answer

Try this instead

local player = game.Players.LocalPlayer
 
-- Paste script into a LocalScript that is 
-- parented to a Frame within a Frame
local frame = script.Parent
local container = frame.Parent
container.BackgroundColor3 = Color3.new(0, 0, 0) -- black
 
-- This function is called when the humanoid's health changes
local function onHealthChanged()
	local human = player.Character.Humanoid
	local percent = human.Health / human.MaxHealth
	-- Change the size of the inner bar
	frame.Size = UDim2.new(percent, 0, 1, 0)
	-- Change the color of the health bar
	if percent < .1 then
		frame.BackgroundColor3 = Color3.new(1, 0, 0) -- black
	elseif percent < .4 then
		frame.BackgroundColor3 = Color3.new(1, 1, 0) -- yellow
	else
		frame.BackgroundColor3 = Color3.new(0, 1, 0) -- green
	end
end
 
-- This function runs is called the player spawns in
local function onCharacterAdded(character)
	local human = character:WaitForChild("Humanoid")
	-- Pattern: update once now, then any time the health changes
	human.HealthChanged:Connect(onHealthChanged)
	onHealthChanged()
end
 
-- Connect our spawn listener; call it if already spawned
player.CharacterAdded:Connect(onCharacterAdded)
if player.Character then
	onCharacterAdded(player.Character)
end

This is from the roblox wiki

instead

1 comment

0

Change the character for the NPC

This discussion is preserved as it was. New answers, comments, and votes are closed.