ZhaMenIconCtrl.cs 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using UnityEngine;
  5. using UnityEngine.Events;
  6. using UnityEngine.EventSystems;
  7. using UnityEngine.UI;
  8. using UnityEngine.UIElements;
  9. public class ZhaMenIconCtrl : MonoBehaviour, IPointerEnterHandler, IPointerExitHandler
  10. {
  11. private RectTransform rect;
  12. private Camera _camera;
  13. private UnityEngine.UI.Button _button;
  14. public FloodGate _data;
  15. public Transform targetTransForm;
  16. public GameObject tint;
  17. public Text tintName;
  18. public void Init(FloodGate data,string name,GameObject targetObj,UnityAction clickAction)
  19. {
  20. _data = data;
  21. tintName.text = name;
  22. rect = this.GetComponent<RectTransform>();
  23. _button = this.transform.Find("Icon").GetComponent<UnityEngine.UI.Button>();
  24. _button.onClick.AddListener(
  25. clickAction
  26. );
  27. rect.anchoredPosition = new Vector2(2000, 0);
  28. _camera = CameraManager.instance.mainCamera;
  29. targetTransForm = targetObj.transform;
  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. public void OnPointerEnter(PointerEventData eventData)
  55. {
  56. tint.gameObject.SetActive(true);
  57. LayoutRebuilder.ForceRebuildLayoutImmediate(tintName.GetComponent<RectTransform>()); // 强制重新计算布局
  58. LayoutRebuilder.ForceRebuildLayoutImmediate(tint.GetComponent<RectTransform>()); // 强制重新计算布局
  59. }
  60. public void OnPointerExit(PointerEventData eventData)
  61. {
  62. tint.gameObject.SetActive(false);
  63. }
  64. }