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 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM