How can I do health bar follows enemy?

Hi! I’m almost started to learning javascript and I’m doing exercises to get understanding of scripting. I’m trying to make a health bar following an enemy AI, but I don’t know how to do it.

I’m not looking for someone how make the script for me, I just want someone try explain me how to do it because I tried so many times and I failed.

static var maxHealth : float = 100 ;
static var currentHealth : float;
var dmg : float;

var maxHealthtex : Texture2D;
var currentHealthtex : Texture2D;

var hpBarLenght : float;
var percentOfHp : float;

...

function Update () {
percentOfHp = currentHealth/maxHealth;
hpBarLenght = percentOfHp * 100;
}
   
function OnGUI() {
if (currentHealth > 0) {
GUI.DrawTexture(Rect(10, 10, hpBarLenght, 20), currentHealthtex);
}
}

I don’t know how can I make GUI coordinates follows enemy.

Some suggestions?

Use : Camera.WorldToScreenPoint()

Get the on-screen position from the main camera


	var targetObject : Transform;
	var onScreenPosition : Vector3;
	onScreenPosition = Camera.main.WorldToScreenPoint(targetObject.position);

Then display the health bar above the targetObject(the enemy)


	var displayRect : Rect;
	displayRect = Rect(onScreenPosition.x - 50, Screen.height-(onScreenPosition.y + 45), 100, 20);

	GUI.DrawTexture(displayRect, maxHealthtex);
	displayRect.width = hpBarLenght;
	GUI.DrawTexture(displayRect, currentHealthtex);