ScrollRectPassThroughComp.cs 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. namespace Plugins.CxShine.UIUtil
  2. {
  3. using UnityEngine;
  4. using UnityEngine.UI;
  5. using UnityEngine.EventSystems;
  6. [RequireComponent(typeof(ScrollRect))]
  7. public class ScrollRectPassThroughComp : MonoBehaviour, IPointerDownHandler, IPointerUpHandler
  8. {
  9. private ScrollRect scrollRect;
  10. private bool isPointerDown = false;
  11. private void Awake()
  12. {
  13. // 添加GraphicRaycaster组件
  14. gameObject.AddComponent<GraphicRaycaster>();
  15. // 添加EventSystem组件
  16. if (FindObjectOfType<EventSystem>() == null)
  17. {
  18. GameObject eventSystem = new GameObject("EventSystem");
  19. eventSystem.AddComponent<EventSystem>();
  20. eventSystem.AddComponent<StandaloneInputModule>();
  21. }
  22. scrollRect = GetComponent<ScrollRect>();
  23. }
  24. public void OnPointerDown(PointerEventData eventData)
  25. {
  26. isPointerDown = true;
  27. CheckPassThrough(eventData);
  28. }
  29. public void OnPointerUp(PointerEventData eventData)
  30. {
  31. isPointerDown = false;
  32. }
  33. private void CheckPassThrough(PointerEventData eventData)
  34. {
  35. if (isPointerDown)
  36. {
  37. // 计算指针位置和ScrollRect的相对位置
  38. Vector2 localPoint;
  39. RectTransformUtility.ScreenPointToLocalPointInRectangle(scrollRect.content, eventData.position, eventData.pressEventCamera, out localPoint);
  40. // 如果指针在ScrollRect的范围内,则透传事件
  41. if (scrollRect.content.rect.Contains(localPoint))
  42. {
  43. eventData.pointerPressRaycast = eventData.pointerCurrentRaycast;
  44. }
  45. }
  46. }
  47. }
  48. }