ShuiYaIconCtrl.cs 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEngine.UI;
  5. public class ShuiYaIconCtrl : MonoBehaviour
  6. {
  7. private RectTransform rect;
  8. private Camera _camera;
  9. public ShuiYaData _data;
  10. private Text valueText;
  11. private Text nameText;
  12. public Transform targetTransForm;
  13. public void Init(ShuiYaData data)
  14. {
  15. _camera = CameraManager.instance.mainCamera;
  16. _data = data;
  17. rect = this.GetComponent<RectTransform>();
  18. rect.anchoredPosition = new Vector2(2000, 0);
  19. nameText = this.transform.Find("nameText").GetComponent<Text>();
  20. nameText.text = $"{_data.name}水压";
  21. valueText = this.transform.Find("valueText").GetComponent<Text>();
  22. valueText.text = $"{data.value} <size=12><color=FFFFFF>mm</color></size>";
  23. }
  24. void Update()
  25. {
  26. if (targetTransForm != null)
  27. {
  28. if (IsObjectInCameraView(targetTransForm, _camera))
  29. {
  30. rect.transform.position=_camera.WorldToScreenPoint(targetTransForm.position);
  31. }
  32. else
  33. {
  34. rect.transform.position = new Vector3(2000, 0, 0);
  35. }
  36. }
  37. }
  38. bool IsObjectInCameraView(Transform objectTransform, Camera camera)
  39. {
  40. Vector3 objectScreenPosition = camera.WorldToScreenPoint(objectTransform.position);
  41. return objectScreenPosition.z > 0 &&
  42. objectScreenPosition.x > 0 &&
  43. objectScreenPosition.x < Screen.width &&
  44. objectScreenPosition.y > 0 &&
  45. objectScreenPosition.y < Screen.height;
  46. }
  47. }