LabelObjectScript.cs 1.4 KB

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