UI Attached to Gameobject via Overlay?

Hi all,

I can’t seem to find any solid answers for this unless this is called something else and I am looking at the wrong material.

My end goal is to create UI that follows a GameObject. An example would be a health bar. I want it to render as if the canvas is set to Screen Space -Overlay, and only be rendered when the GameObject in question comes into the camera view. I have done this but its offset so I am guessing its my code - I picked up a method off of Unity3d answers which is run on the Image

            Vector3 pos;
            float width = canvas.GetComponent<RectTransform>().sizeDelta.x;
            float height = canvas.GetComponent<RectTransform>().sizeDelta.y;
            float x = Camera.main.WorldToScreenPoint(t.position).x / Screen.width;
            float y = Camera.main.WorldToScreenPoint(t.position).y / Screen.height;
            pos = new Vector3(width * x - width / 2, y * height - height / 2);
            return pos;

I had a system like this in the old GUI however this is obviously no longer feasible. I have tried attaching the canvas to the GameObject however it rotates with the GameObject. I didn’t consider putting constraints on the rotation as even then it didn’t look so great. Is there a best practice way of doing this?

Thanks for any answers

EDIT: So by adding in some values to offset the x and y in the above code I can get it to work as I want but this seems hacky and uncessary :confused:

EDIT2: Also it seems choppy? The gameobject moves around via navmesh and I have tried various updates for the above script to be run in however the UI just trails a small amount and has jerky movement any ideas?

Well one point I’d make is that you are repeatedly calling GetComponent, for performance sake, just make that call once and use the reference. Same with the Camera calls.

Ideally you should be using the pointer event data rather than re-querying the input system each frame. I would recommend looking at the IPointerHandler events and building scripts with them

As to the offsets, what style of canvas are you using? If you are using one of the camera modes, you should be using the camera attached to that canvas rather than main.