You may want a world space canvas. Which allows you to place text into the world vs as an overlay type effect. But you’ll have to see if that is what you want to consider if it works for you.
public GameObject target;
Rect rect = new Rect(0, 0, 300, 100);
Vector3 offset = new Vector3(0f, 0f, 0.5f); // height above the target position
void OnGUI()
{
Vector3 point = Camera.main.WorldToScreenPoint(target.position + offset);
rect.x = point.x;
rect.y = Screen.height - point.y - rect.height; // bottom left corner set to the 3D point
GUI.Label(rect, target.name); // display its name, or other string
}
Just took a look at the code I use that’s working. I use screen space overlay, and call the below in LateUpdate only after the camera has moved. I actually have the camera script call a list of delegates, which then calls this code on the floating UI object.
if (AnchorRectTransform == null)
{
AnchorRectTransform = GetComponent<RectTransform>();
}
Vector3 screenPosition = Camera.main.WorldToScreenPoint(CameraPointAboveShip.position);
//Debug.Log(screenPosition);
if (screenPosition.z < 0f) //Disable display when behind the camera
{
enableDisplay(false);
}
else
{
enableDisplay(true);
}
AnchorRectTransform.anchoredPosition = screenPosition;
All enableDisplay does is switch the CanvasGroup.alpha between 0f and 1f. I don’t remember if that was actually important to do or not. I use Camera.main instead of a cached reference to the camera, because in my game the player is switching between several main cameras.
This is the bare minimum of information to report:
what you want
what you tried
what you expected to happen
what actually happened, log output, variable values, and especially any errors you see - links to documentation you used to cross-check your work (CRITICAL!!!)
The purpose of YOU providing links is to make our job easier, while simultaneously showing us that you actually put effort into the process. If you haven’t put effort into finding the documentation, why should we bother putting effort into replying?
Do not TALK about code without posting it. Do NOT retype code. Copy/paste and post code properly. ONLY post the relevant code, and then refer to it in your discussion.