Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

Why is Humanoid.Health is returning the max health instead of the current health?

Asked by 4 years ago

I'm trying to make a custom health bar for my enemy NPC. There is a Frame inside of a screenGUI representing the enemy health. The Humanoid for the enemy named "StalinCat" is called enemy. Here's my script.

local enemy = game.Workspace.StalinCat.Enemy
local frame = script.Parent

local function onHealthChanged()
    local percent = enemy.Health/enemy.MaxHealth
    frame.Size = UDim2.new(0,percent*554,0,7)
    print("Health = ", enemy.Health)
    print("MaxHealth = ", enemy.MaxHealth)
end
enemy.Changed:Connect(onHealthChanged)
onHealthChanged()

When I damage the enemy, the health bar does not change. Only when the enemy is dead does the health bar become zero. I tried printing out the enemy's health and max health while I was debugging, both of them output 44(The max health), even when the enemy was damaged.

What am I doing wrong? `

1 answer

Log in to vote
2
Answered by 4 years ago

I recommend using HealthChanged which is an event for a Humanoid that fires each time the Humanoid's health changes. I also recommend using the current health parameter of HealthChanged which contains the new Humanoid.Health value of the enemy.

local enemy = game.Workspace.StalinCat.Enemy
local frame = script.Parent

local function onHealthChanged(currentHealth)
    local percent = currentHealth/enemy.MaxHealth
    frame.Size = UDim2.new(0, percent*554, 0, 7) --I don't exactly see why you're multiplying the percentage by 554, but I'll just leave it here and allow you to edit it to fit your frame. 
--Either way, i recommend you using the first and third values of UDim2.new (xScale and yScale). As they are used to let the GUI scale to the player's screen resolution
    print("Health = ", currentHealth)
    print("MaxHealth = ", enemy.MaxHealth)
end 

enemy.HealthChanged:Connect(onHealthChanged)
0
Thank you for your response! I replaced my code with yours, however, I'm getting the same issue. The healthchanged event is not firing when I am clearly damaging the enemy, and the onHealthChanged function doesn't run. totoisdog2003 0 — 4y
0
That code works for me, maybe it's because the script can't find a Humanoid named "Enemy" in "StalinCat". Try using WaitForChild on the Enemy Humanoid. Godlydeathdragon 227 — 4y
Ad

Answer this question