Unity3d how to have a "text label" follow a game object

In my world I have a GameObject, lets say a race car.

Above the race car I want a white box with a text label that says the driver's name (let's say "Fred"). This label will follow the race car as it moves.

How can I create this "white box with a text label" in Unity? Will it be a gameobject (if so, how do I construct it).

Since the only "Text" object I find in Unity editor was a UI element. And the UI canvas is unrelated to the coordinates in my game world, so I dont know if this is appropriate use case for this type of object.

car with a name tag


Solution 1:

I think you have 2 options. It is fundamental to read to the different canvas modes in the documentation

1.- Overlay mode. You can figure out the screen position of your canvas at runtime with
Camera.WorldToScreenPoint. This canvas mode places UI elements on the screen rendered on top of the scene, so you would kind of "fake" the canvas is following your gameObject in the world calculatig and updating its position.

2.- World Space, make cavas children of your car and make it always face the camera with a billboard component updating the canvas rotation.

public class Billboard : MonoBehaviour {
    public Transform cam;
    private void Start() {
        cam = Camera.main.transform;
    }
    void LateUpdate() {
        transform.LookAt(transform.position + cam.forward);
    }
}

Add the component to the canvas gameObject or do myCanvas.AddComponent<Billboard>(); where myCanvas is the Canvas component in your canvas holder gameObject. With this option the canvas is actually in the world as the mode name indicates, thats why you would need to update its rotation to make it always look to the camera.

In option 1 you need to update the position and not the rotation because the canvas is in the screen and with option 2 you need to update the rotation and not the position because the canvas is in the world.