Display GUIText above a GameObject

I try to display a GUIText above a NPC that includes the name of it and it works just fine for me, but when I move the camera in the y directions the GUIText moves up and down.

Does anyone know how to display a GUIText above a GameObject so it stays where I put it ?

Here is what I have so far:

using UnityEngine;
using System.Collections;

[RequireComponent (typeof(GUIText))]
public class NPCTag : MonoBehaviour
{
    public Transform npcNamePos;
    public string npcName;

    Camera cam;
    Vector2 screenPos;
    GUIText npcGui;

    void Start ()
    {
        cam = Camera.main;
        npcNamePos = GameObject.Find("npcNamePos").transform;
        npcGui = GetComponent<GUIText>();
	}
	
	void Update ()
    {
        screenPos = cam.WorldToScreenPoint(npcNamePos.position);
        Debug.Log("The position of the NPC is: " + screenPos);
	}

    void OnGUI()
    {
        var centeredStyle = GUI.skin.GetStyle("Label");
        centeredStyle.alignment = TextAnchor.UpperCenter;
        npcGui.material.color = Color.green;
        GUI.TextField(new Rect(screenPos.x, screenPos.y, 100, 50), npcName);
    }
}

Thanks for you support!

This problem’s really very simple to solve, and is really only an issue due to differences in position formatting between various 3D interfaces.

The Y-position on the screen and the Y-position returned by WorldToScreenPoint() are opposites. That said, this means that this is actually a very easy problem to solve.

GUI.TextField(new Rect(screenPos.x, Screen.height - screenPos.y, 100, 50), npcName);

“Screen.height - screenPos.y” will give you the opposite location relative to your screen’s dimensions, which is exactly what you’ll want to position the text adequately.