Hello everyone, Yesterday I tried to add a health bar to an in-game NPC. And the issue with it is that the Humanoid.ChangedHealth event doesn’t run at all. I tried using Changed and GetPropertyChangedSignal, but with no success. This is the script:
local humanoid = script.Parent.Parent.Parent:WaitForChild("Humanoid")
local TextLabel = script.Parent:WaitForChild("HealthLabel")
local Head = script.Parent.Parent
local HealthBar = script.Parent
local GreenBar = script.Parent:WaitForChild("GreenBar")
TextLabel.Text = humanoid.Health.. " HP / " ..humanoid.MaxHealth.. " HP"
humanoid.HealthChanged:Connect(function()
TextLabel.Text = humanoid.Health.. " HP / " ..humanoid.MaxHealth.. " HP"
print("life changed")
end)
The script is located in a Billboard in the Characters head. I tried making a new NPC, that was to no success either. Thank you for your help in advance.
There should be errors or warnings that show up in the output. The only theories I have, given the above information, are:
humanoid is not found.
The name of the Humanoid may have changed, or is initially different.
WaitForChild is misused. See second theory.
The location of the Humanoid relative to the Script is different. Assuming the GUI is a descendant of a Model, use FindFirstAncestorWhichIsA. See the modified code below.
WaitForChild is not appropriately used.
Only use WaitForChild if you expect an object to be inserted at a later time.
A better alternative is to just use FindFirstChild and other similar functions, particularly FindFirstChildWhichIsA. This function will check for an Instance that inherits a certain class (or is related to the object type).
Usage: local humanoid = parent:FindFirstChildWhichIsA("Humanoid")
Modified code:
The following code is not tested.
local Character = script:FindFirstAncestorWhichIsA("Model")
local Head = Character:FindFirstChild("Head")
local Humanoid = Character:FindFirstChildWhichIsA("Humanoid")
if not Humanoid then
error("Humanoid not found.")
end
local gui = script.Parent
local healthBar = gui
local greenBar = gui.GreenBar
local healthLabel = gui.HealthLabel
local function refreshHealthBar()
healthLabel.Text = `{Humanoid.Health} / {Humanoid.MaxHealth} HP`
print("life changed")
end
refreshHealthBar()
Humanoid.HealthChanged:Connect(refreshHealthBar)
@Y_VRNDLL The code you provided still doesn’t work, the code runs one time at the start and makes the HealthLabel = 100 / 100 HP. Also, the code runs the second time when the NPC dies showing 0/100. I’ve changed all the WaitForChild functions I had, but that doesn’t resolve the main issue, but thanks for making my code a bit neater :"). So basically to summarize the problem again, the code finds the Humanoid, changes it’s parameters once, and then does it again only when the player dies. Soo I still believe it’s the HealthChanged event that’s not working properly. Thank you for your response.