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.
01 | local enemy = game.Workspace.StalinCat.Enemy |
02 | local frame = script.Parent |
03 |
04 | local function onHealthChanged() |
05 | local percent = enemy.Health/enemy.MaxHealth |
06 | frame.Size = UDim 2. new( 0 ,percent* 554 , 0 , 7 ) |
07 | print ( "Health = " , enemy.Health) |
08 | print ( "MaxHealth = " , enemy.MaxHealth) |
09 | end |
10 | enemy.Changed:Connect(onHealthChanged) |
11 | 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? `
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.
01 | local enemy = game.Workspace.StalinCat.Enemy |
02 | local frame = script.Parent |
03 |
04 | local function onHealthChanged(currentHealth) |
05 | local percent = currentHealth/enemy.MaxHealth |
06 | frame.Size = UDim 2. 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) |
10 | end |
11 |
12 | enemy.HealthChanged:Connect(onHealthChanged) |