LabelObjectScript.cs 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEngine.UI;
  5. public class LabelObjectScript : MonoBehaviour
  6. {
  7. Camera camera;
  8. public GameObject target;
  9. public RectTransform canvasRect;
  10. public GameObject text;
  11. // Start is called before the first frame update
  12. void Start()
  13. {
  14. //text = Instantiate(Resources.Load("GameObjects/Capsule", typeof(GameObject))) as GameObject;
  15. }
  16. // Update is called once per frame
  17. void Update()
  18. {
  19. // Offset position above object bbox (in world space)
  20. float offsetPosY = target.transform.position.y + 1.5f;
  21. // Final position of marker above GO in world space
  22. Vector3 offsetPos = new Vector3(target.transform.position.x, offsetPosY, target.transform.position.z);
  23. // Calculate *screen* position (note, not a canvas/recttransform position)
  24. Vector2 canvasPos;
  25. Vector2 screenPoint = Camera.main.WorldToScreenPoint(offsetPos);
  26. // Convert screen position to Canvas / RectTransform space <- leave camera null if Screen Space Overlay
  27. RectTransformUtility.ScreenPointToLocalPointInRectangle(canvasRect, screenPoint, null, out canvasPos);
  28. // Set
  29. //markerRtra.localPosition = canvasPos;
  30. text.transform.localPosition = canvasPos;
  31. }
  32. }