UGUI多个ScrollRect嵌套拖动

时间:2020-04-13 15:16:36   收藏:0   阅读:129
技术分享图片
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

原文:https://www.cnblogs.com/Joke-crazy/p/12691067.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!