Health Bar / GUI issues (WorldToScreenPoint)

I’m getting to grips with most of the 3d Stuff in Unity, I have the guts of a tower defence game written, but I’m having trouble with all the GUI stuff.

at the moment I’m just trying to get health-bars to appear above the top of each creep. and I’m not even worried about the shrinking of the healthbar(yet), I just can’t get it to appear at the right spot on the screen.

Here’s my code:

var FollowTarget: Transform;

function OnGUI() {
	theCam = Camera.main;
	var screenPos : Vector3 = theCam.WorldToScreenPoint (FollowTarget.position);
	
	HealthBarX = screenPos.x;
	HealthBarY = screenPos.y;
	
	GUI.Box(Rect(HealthBarX,HealthBarY,70,5),"This is a title");
}

The above code gives the following output:

[health bar issues (Tower Defence game)][1]

(I can’t upload to Unity Answers because it just won’t take the JPG for some reason)

and I modified some of the code to get it to work on my screen:

screenHeight = Screen.currentResolution.height;
HealthBarX = screenPos.x - 35;
HealthBarY = screenHeight - 170 - screenPos.y;

However that’s great for my Resolution in the Unity window, but that will all change depending on resolution so I’m looking for some way to get it to appear directly at the point on screen where the enemy is showing…

Any ideas ?
[1]: health bar issues (Tower Defence game)

This should help you with your issue.

using UnityEngine;
using System.Collections;
public class NewBehaviourScript : MonoBehaviour {

public Transform target;
private static int healthbarwidth = 70;

// Use this for initialization
void Start () {

}

// Update is called once per frame
void Update () {

}

void OnGUI()
{
    Camera cam = Camera.main;

    Vector3 screenPos = cam.WorldToScreenPoint(target.position);

    Debug.Log(screenPos.ToString());

    GUI.Box(new Rect(screenPos.x - healthbarwidth/2, Screen.height - screenPos.y, 70, 5), "Title");

}

}

The problem you were facing is that the Camera and screen use the y coordinate in an opposite manner to each other. So your Y coordinate is actually:

Screen.height - screenPos.y