Enemy Health Bar problem Unity 2D.

Hi all,

I am building a tower defense game. I have an enemy prefab with a EnemyHealthBar empty game object attached to it, Health & Health-bg are both children objects and make up the health bar. I have the code to rescale my health bar upon taking damage however it doesn’t seem to be working as expected.

My logic is working correctly, when the turret fires and hits a minion it deducts a life point out of a total of 6 and when it hits 0 the prefab enemy is destroyed. However my Health bar starts out like this:

24443-untitled.png

After one hit it looks like this:

24444-untitled1.png

I can’t upload another photo so to describe the last hit before death but its the same as picture 2 however the boxes are next to each other, separated by a few pixels. They’re both a sixth of the original size.

Any help much appreciated!

Below is my health bar code:

public class UIHealthBar: MonoBehaviour {
		
		public float initialGreenLength;
		public GameObject healthBar;
		public float curHealth;
		public float maxHealth;
		public float lastHealth;
		EnemyOgre healthScript;
		
		Vector3 greenPos;
		Vector3 greenScale;
		
		public float timer;
		
		void Awake ()
		{
			
			//loads enemy health value from healthScript
			healthScript = transform.parent.gameObject.GetComponent<EnemyOgre>();
			curHealth = healthScript.ogreHealth;
			maxHealth = healthScript.maxHealth;
			initialGreenLength=healthBar.transform.localScale.x;
			
			//stores two health values, will come in later
			lastHealth = curHealth;
		}
		
		
		void Update () 
		{
			
			timer -= Time.deltaTime;
			
			
			if(timer <= 0)
			{
				timer = 0.05f;
				
				// adjusts the greenHealthBar so that as the enemy takes damage
				// the bar shifts to the left, making it appear that the damage
				// is coming off the right side of the bar and not equally from
				// each end.

			if(lastHealth > curHealth)
			{
				greenPos = healthBar.transform.localPosition;
				greenPos.x = (lastHealth - curHealth)/curHealth;
				healthBar.transform.localPosition = greenPos;
				lastHealth = curHealth;
			}
			
			curHealth = healthScript.ogreHealth;
			maxHealth = healthScript.maxHealth;

			greenScale = healthBar.transform.localScale;
			greenScale.x = greenScale.x * (curHealth/maxHealth);
			transform.localScale = greenScale;
			
		}
	}
}

Do the white frame and the green health bar have the same position initially? I’m thinking that they have different origins in relation to the centre points, so initially it is ok because you never set the position of the green bar to the frame, but once you set it, it is off because of the difference of the points of origin.