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 5 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.

01local enemy = game.Workspace.StalinCat.Enemy
02local frame = script.Parent
03 
04local function onHealthChanged()
05    local percent = enemy.Health/enemy.MaxHealth
06    frame.Size = UDim2.new(0,percent*554,0,7)
07    print("Health = ", enemy.Health)
08    print("MaxHealth = ", enemy.MaxHealth)
09end
10enemy.Changed:Connect(onHealthChanged)
11onHealthChanged()

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 5 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.

01local enemy = game.Workspace.StalinCat.Enemy
02local frame = script.Parent
03 
04local function onHealthChanged(currentHealth)
05    local percent = currentHealth/enemy.MaxHealth
06    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.
07--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
08    print("Health = ", currentHealth)
09    print("MaxHealth = ", enemy.MaxHealth)
10end
11 
12enemy.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 — 5y
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 — 5y
Ad

Answer this question