UGUI解决嵌套使用多个ScrollRect时的Drag拖动冲突问题
很简单,直接看代码:
1 using UnityEngine.UI; 2 using UnityEngine.EventSystems; 3 using UnityEngine; 4 5 /// <summary> 6 /// 解决嵌套使用ScrollRect时的Drag冲突问题。请将该脚本放置到内层ScrollRect上(外层的ScrollRect的Drag事件会被内层的拦截) 7 /// </summary> 8 public class NestedScrollRect : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler 9 { 10 /// <summary> 11 /// 外层被拦截需要正常拖动的ScrollRect,可不指定,默认在父对象中找 12 /// </summary> 13 public ScrollRect anotherScrollRect; 14 /// <summary> 15 /// 当前的ScrollRect(本脚本所放置的物体上)的拖动方向默认为上下拖动,否则为左右拖动型 16 /// </summary> 17 public bool thisIsUpAndDown = true; 18 19 private ScrollRect thisScrollRect; 20 21 void Awake () 22 { 23 thisScrollRect = GetComponent<ScrollRect> (); 24 if (anotherScrollRect == null) 25 anotherScrollRect = GetComponentsInParent<ScrollRect> ()[1]; 26 } 27 28 public void OnBeginDrag (PointerEventData eventData) 29 { 30 anotherScrollRect.OnBeginDrag (eventData); 31 } 32 33 public void OnDrag (PointerEventData eventData) 34 { 35 anotherScrollRect.OnDrag (eventData); 36 float angle = Vector2.Angle (eventData.delta, Vector2.up); 37 //判断拖动方向,防止水平与垂直方向同时响应导致的拖动时整个界面都会动 38 if (angle > 45f && angle < 135f) 39 { 40 thisScrollRect.enabled = !thisIsUpAndDown; 41 anotherScrollRect.enabled = thisIsUpAndDown; 42 } 43 else 44 { 45 anotherScrollRect.enabled = !thisIsUpAndDown; 46 thisScrollRect.enabled = thisIsUpAndDown; 47 } 48 } 49 50 public void OnEndDrag (PointerEventData eventData) 51 { 52 anotherScrollRect.OnEndDrag (eventData); 53 anotherScrollRect.enabled = true; 54 thisScrollRect.enabled = true; 55 } 56 }