Can anyone help me with a coding query?

I’m having issues creating health bars that float over my characters within my game in Unity. I have health bars coded in already, but they are only at the top of the screen.

Here is the code that I have so far :

var maxHealth : int = 50;

var curHealth : int = 50;

var healthBarLength : float;

function OnGUI() : void
{
	GUI.Box(new Rect(537, 10, healthBarLength, 20), curHealth + "/" + maxHealth);
}

public function AdjustCurrentHealth(adj:int) : void
{
	curHealth += adj;
	if (curHealth <= 0)
	{
		curHealth = 0;
		//OnDeath();
	}
	
	if (maxHealth < 1)
	{
		maxHealth = 1;
	}
	
	var floatMaxHealth:float = maxHealth;
	healthBarLength = (Screen.width / 2) * (curHealth / floatMaxHealth);
}

Any idea how I can take this and change it so that it floats above the head of my character at all times so that I can free up more space on the screen?

So the issue is that you have a health bar, that is always in the same position? But you want one over the head of any enemy? If yes, just lose the OnGuI() aspect. Create object healthBar. Prefab object healthBar. Place object healthBar over the head of enemy. In enemy code, make any damage enemy takes reflect in the health bar.

Determine the screen coordinates of the character’s world space position and draw there. This approach can be used within the OnGUI() phase of rendering. Similar in principle to what I do below to render name tags:

  float r = ((SphereCollider)s.UnityObject.collider).radius * 0.5f;
  Vector3 screenPoint = MainCamera.Instance.camera.WorldToScreenPoint(new Vector3(s.UnityObject.transform.position.x + r, s.UnityObject.transform.position.y, s.UnityObject.transform.position.z + r));
  GUI.Label(new Rect(screenPoint.x, Screen.height - screenPoint.y, 100, 22), player.Username);

Key function call is WorldToScreenPoint

Both of these actually ended up working out for me so thank you both very much. Now I just need to decide which one works out for me better haha.