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 }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!