How to always orient the object text to camera ?


I have this code but I don’t know what I am doing wrong because my spawned bar with Text Mesh is not always straight toward the camera. Sometimes it is rotated by a certain degree. Please help!

using UnityEngine;
    public class TownIndicator : MonoBehaviour
    public Font font;
    public int fontSize = 8;
    public Vector3 Offset =; // The offset from the character
    public float health ;
    private TextMesh bar;
    void Start()
    // Setup the text mesh
    bar = new GameObject("HealthBar").AddComponent("TextMesh") as TextMesh;
    bar.gameObject.transform.parent = transform;
    bar.transform.localPosition = + Offset;
    if(font) bar.font = font;
    else bar.font =;
    bar.renderer.material = font.material;
    bar.characterSize = 0.25f;
    bar.alignment = TextAlignment.Center;
    bar.anchor = TextAnchor.MiddleCenter;
    bar.fontSize = fontSize;
    void Update()
    // Hook up your health variable here
    bar.text = ""+ health.ToString();

Its not really clear what you try to achieve.

If you just want to display some text on top of some 3D-object, then why don’t you use the OnGUI callback? It would be the simplest thing instead of creating a new game object and aligning it every frame.

The only tricky thing is to get the 2d screen coordinate. OnGUI works in “GUI-coordinates”, whereas Camera.WorldToScreenPoint returns “screen coordinates”. Its basically inverted on the y-axis.

Something like this should get you started:

public string health;

void OnGUI()
	Vector3 pos = Camera.main.WorldToScreenPoint(transform.position);
	GUI.Label(new Rect(pos.x, Screen.height - pos.y, 100, 30), health);

If you insist on an own game object, you can at least use a GUIText, which is auto-aligned towards the camera. Your camera will need an GUILayer component for it to work.