PcoWSkbVqDnWTu_dm2ix
We use cookies on this site to enhance your user experience
Collapse Sidebar

HealthChanged

Fires when the Humanoid/Health changes to a value equal or below the Humanoid/MaxHealth value.

This event can be used to show custom heatlh bars.

When Humanoid/Health reaches zero, the Humanoid will die and the Humanoid/Died event will fire. This event will fire with a value of zero.

Parameters

Name Type Default Description

The new value of Humanoid/Health


Code Samples


Health Bar

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

Humanoid.HealthChanged

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)