This event fires when the
Humanoid/Health changes. However, it will not fire if the health is increasing from a value equal to or greater than the
Humanoid/Health reaches zero, the
Humanoid will die and the
Humanoid/Died event will fire. This event will fire with a value of zero.
The new value of
The following example determines the change in health, printing it to the output. It will only work in a LocalScript.
local humanoid = game.Players.LocalPlayer.Character.Humanoid local currentHealth = humanoid.Health humanoid.HealthChanged:Connect(function(health) local change = math.abs(currentHealth - health) print("The humanoid's health "..(currentHealth > health and "decreased by " or "increased by ")..change..".") currentHealth = health end)
This code sample allows you to create a simple color-changing health bar using two nested Frames. Paste this into a LocalScript on the inner frame.
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