• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
~Joke_crazy
爱生活,爱拉芳!
   首页    新随笔       管理     

UGUI多个ScrollRect嵌套拖动

using UnityEngine.EventSystems;

namespace UnityEngine.UI
{
    /// <summary>
    /// 解决嵌套使用ScrollRect时的Drag冲突问题。请将该脚本放置到内层ScrollRect上(外层的ScrollRect的Drag事件会被内层的拦截)
    /// </summary>
    public class MultiScroll : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler
    {
        [SerializeField]
        private ScrollRect scroll_parent;

        private ScrollRect scroll_this;

        private float angle;

        [SerializeField]
        private bool horizontalOrVertical;

        private bool direction;

        void Awake()
        {
            scroll_this = GetComponent<ScrollRect>();

            if (scroll_parent == null)
                scroll_parent = GetComponentsInParent<ScrollRect>()[1];
        }

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

        public void OnDrag(PointerEventData eventData)
        {
            scroll_parent.OnDrag(eventData);

            //判断拖动方向,防止水平与垂直方向同时响应导致的拖动时整个界面都会动
            angle = Vector2.Angle(eventData.delta, Vector2.up);

            direction = angle > 45f && angle < 135f;

            if (direction)
            {
                //Horizontal
                scroll_parent.enabled = !horizontalOrVertical;
                scroll_this.enabled = horizontalOrVertical;
            }
            else
            {
                //Vertical
                scroll_this.enabled = !horizontalOrVertical;
                scroll_parent.enabled = horizontalOrVertical;
            }
        }

        public void OnEndDrag(PointerEventData eventData)
        {
            scroll_parent.OnEndDrag(eventData);
            scroll_parent.enabled = true;
            scroll_this.enabled = true;
        }
    }
}
View Code

转载:https://www.cnblogs.com/suoluo/p/5643885.html

posted @ 2020-04-13 14:09  ~Joke_crazy  阅读(228)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3