Making healthbar follow enemy gameobject

Hi, I’m trying to set up a health bar system for a 2D game made in 3D engine. X is horizontal and Z is vertical. I have most of it working, but I can’t get the enemy health bar to follow the enemy. This is my code: (C#)

void OnGUI(){
	Vector3 targetPos = Camera.main.WorldToScreenPoint(transform.position);


		GUI.DrawTexture(new Rect(targetPos.x -30, targetPos.z, 60, 20), background);
		GUI.Box(new Rect (targetPos.x -30, targetPos.z, 60, 20), curHealth + "/"	+ maxHealth);
	}

It’s OK on the X axis, but on the Z axis the healthbar just stays at the top of the screen. I’ve probably spent 10-15 hours googling for answers and trying things that haven’t worked out. I’m sure it’s a tiny thing I’m doing wrong, but I’m a complete noob and can’t figure it out. Greatly appreciate any help.

GUI uses GUI coordinates, not screen coordinates. GUI coordinates start in the upper left corner, screen coordinates start in the lower right. So at line 3 do:

targetPos.y = Screen.height - targetPos.y;