UI Follow Scene Objects?

How do I make a UI that follows an object (eg, a healthbar that always stays the same size no matter how far the object is from the camera?

My current setup that isn’t working:

I have a Screen Space - Camera canvas set to “Scale with screen size” 1136 x 640 and the slider is set to Height (1).

There is a cube in the scene.

I have an image in the canvas with a script on it that moves its position every frame with the following code:

using UnityEngine;
using System.Collections;

public class TrackObject : MonoBehaviour {
    public GameObject Obj;

    public Camera mCamera;
    private RectTransform rt;

    void Start ()
    {
        rt = GetComponent<RectTransform>();
    }
   
    void Update ()
    {
        if (Obj != null)
        {
            Vector2 pos = RectTransformUtility.WorldToScreenPoint(mCamera, Obj.transform.position);
            rt.position = pos;
        }
    }
}

But what I’m currently seeing is the UI element move at half the speed of the objects in the camera. What am I doing wrong?

Figured it out. I have to run the screen point through RectTransformUtility.ScreenPointToLocalPointInRectangle() to get the proper local position of the UI element.

2 Likes