Unity UGUI两个scrollRect叠加解决拖拽冲突

代码如下

using UnityEngine.UI;
using UnityEngine.EventSystems;
using UnityEngine;

/// <summary>
/// 解决嵌套使用ScrollRect时的Drag冲突问题。请将该脚本放置到内层ScrollRect上(外层的ScrollRect的Drag事件会被内层的拦截)
/// </summary>
public class NestedScrollRect : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler

{
    /// <summary>
    /// 外层被拦截需要正常拖动的ScrollRect,可不指定,默认在父对象中找
    /// </summary>
    public ScrollRect anotherScrollRect;
    /// <summary>
    /// 当前的ScrollRect(本脚本所放置的物体上)的拖动方向默认为上下拖动,否则为左右拖动型
    /// </summary>
    public bool thisIsUpAndDown = true;
    private ScrollRect thisScrollRect;

    void Awake()
    {
        thisScrollRect = GetComponent<ScrollRect>();
        if (anotherScrollRect == null)
        {
            anotherScrollRect = GetComponentsInParent<ScrollRect>()[1];
        }
    }

    public void OnBeginDrag(PointerEventData eventData)
    {
        anotherScrollRect.OnBeginDrag(eventData);
    }

    public void OnDrag(PointerEventData eventData)
    {
        anotherScrollRect.OnDrag(eventData);
        float angle = Vector2.Angle(eventData.delta, Vector2.up);
        //判断拖动方向,防止水平与垂直方向同时响应导致的拖动时整个界面都会动
        if (angle > 45f && angle < 135f)
        {
            thisScrollRect.enabled = !thisIsUpAndDown;
            anotherScrollRect.enabled = thisIsUpAndDown;
        }
        else
        {
            anotherScrollRect.enabled = !thisIsUpAndDown;
            thisScrollRect.enabled = thisIsUpAndDown;
        }
    }

    public void OnEndDrag(PointerEventData eventData)
    {
        anotherScrollRect.OnEndDrag(eventData);
        anotherScrollRect.enabled = true;
        thisScrollRect.enabled = true;
    }
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值