ShuiWeiCtrl.cs 1.8 KB

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