Unity implements UI elements to follow 3D objects

Time:2020-11-26

In this paper, we share the specific code of unity to implement UI elements following 3D objects for your reference. The specific contents are as follows

Implement UI following 3D objects in different rendering modes of canvas

WhenCanvas.RenderMode For screen space overlayTime

To update the world coordinates of the object into the world coordinates on the screen

using UnityEngine;
using System.Collections;

public class FollowWorldObj : MonoBehaviour {
 [SerializeField]
 GameObject worldpos; // 3D objects (characters)
 [SerializeField]
 Recttransform recttrans; // UI elements (such as blood bar, etc.)
 Public Vector2 offset; // offset

 // Update is called once per frame
 void Update () {
  Vector2 screenPos=Camera.main.WorldToScreenPoint(worldPos.transform.position);
  rectTrans.position = screenPos + offset;
 }
}

WhenCanvas.RenderMode For screen space cameraTime

utilize RectTransformUtility.ScreenPointToLocalPointInRectangle Convert the 2D coordinates of UI elements in canvas:

using UnityEngine;
using System.Collections;
using UnityEngine.EventSystems;

public class UI_FollowObj : MonoBehaviour {
 [SerializeField]
 Camera UI_ Camera; // UI camera
 [SerializeField]
 Recttransform image; // UI element
 [SerializeField]
 GameObject obj; // 3D object
 [SerializeField]
 Canvas ui_Canvas;
 // Update is called once per frame
 void Update () {
  UpdateNamePosition();
 }
 /// <summary>
 ///Update image location
 /// </summary>
 void UpdateNamePosition()
 {
  Vector2 mouseDown = Camera.main.WorldToScreenPoint(obj.transform.position);
  Vector2 mouseUGUIPos = new Vector2();
  bool isRect = RectTransformUtility.ScreenPointToLocalPointInRectangle(ui_Canvas.transform as RectTransform, mouseDown, UI_Camera, out mouseUGUIPos);
  if (isRect)
  {
   image.anchoredPosition = mouseUGUIPos;
  }
 }
}

The results are as follows:

The above is the whole content of this article, I hope to help you in your study, and I hope you can support developeppaer more.