onHealthChanged issue

Hi, I have an issue with my code. I’m trying to make an overhead HP bar but the function is called once or twice when the HP initially changes but not after that.

--//HP handler
local function healthChanged(health, humanoid)
    print("called")
    local MaxHealth = humanoid.MaxHealth
    local CurrentHealth = humanoid.Health

    local InfoUI = humanoid.Parent.Head:WaitForChild("Info")
    local HealthBar = InfoUI.HealthBack.Health
    HealthBar:TweenSize(UDim2.new(CurrentHealth/MaxHealth, 0, HealthBar.Size.Y.Scale, 0),  Enum.EasingDirection.Out, Enum.EasingStyle.Sine, 0.1, false)

    InfoUI.HealthBack.Display.Text = math.round(CurrentHealth) .. "/" .. MaxHealth
    InfoUI.HealthBack.DisplayBACK1.Text = math.round(CurrentHealth) .. "/" .. MaxHealth
end


local function onCharacterAdded(character)
    local Humanoid = character:WaitForChild("Humanoid")
    
    --//HP handler
    Humanoid.HealthChanged:Connect(function(currentHealth)
        healthChanged(currentHealth, Humanoid)
    end)
    
end
1 Like

You could use while wait maybe?

I used while wait to change my health bar

local player = game.Players.LocalPlayer

while wait() do
    local humanoid = game.Workspace:WaitForChild(player.Name):WaitForChild("Humanoid")

    healthChanged(humanoid.Health, humanoid)
end

hope this helps

2 Likes

Thank you, sadly this will not quite work for me as my code is on the server.
Any alternatives that could work by any chance?

Oh, Your code is on the server?

Maybe you could change the healthchanged to getpropertysignalchanged

local function onCharacterAdded(character)
	local Humanoid = character:WaitForChild("Humanoid")
	
	print("CharacterAdded")
	
	Humanoid:GetPropertyChangedSignal("Health"):Connect(function()
		healthChanged(Humanoid.Health, Humanoid)
	end)
end

hope this works!

2 Likes

That helped, thanks a lot mate!

1 Like