unity元件Scroll Rect與其拖拽物體衝突解決辦法
阿新 • • 發佈:2021-06-28
當我們想拖拽ScrollView上面的物體時 向上拖拽會跟ScrollView的向上滑動衝突。
直接看程式碼
我們先建立一個父類
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.EventSystems; using System; public class DragBase : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler { public Action<PointerEventData> beginAction;public Action<PointerEventData> dragingAction; public Action<PointerEventData> endAction; public void OnBeginDrag(PointerEventData eventData) { if (beginAction != null) { beginAction(eventData); } } public void OnDrag(PointerEventData eventData) {if (dragingAction != null) { dragingAction(eventData); } } public void OnEndDrag(PointerEventData eventData) { if (endAction != null) { endAction(eventData); } } }
接下來看一下子類 在大於70度的時候讓ScrollView移動小於的時候則拖拽物體移動
using System.Collections;using System.Collections.Generic; using UnityEngine; using UnityEngine.EventSystems; using UnityEngine.UI; public class DragManager : DragBase { enum DragType { DragSelf, DragScroll, None } DragType dragType = DragType.None; public ScrollRect scrollRect; Vector3 totalDelta = Vector3.zero; void Start() { beginAction = BeginDrag; dragingAction = Draging; endAction = EndDrag; } private void SetDragType(DragType dragType) { this.dragType = dragType; } private bool CheckDragState(DragType state) { return dragType == state; } private void BeginDrag(PointerEventData eventData) { Vector3 delta = eventData.delta; Debug.Log(delta); scrollRect.OnBeginDrag(eventData); totalDelta += new Vector3(Mathf.Abs(delta.x), Mathf.Abs(delta.y), 0); } private void Draging(PointerEventData eventData) { Vector3 delta = eventData.delta; Debug.Log(delta); if (CheckDragState(DragType.None)) { if (Mathf.Abs(delta.y) != Mathf.Abs(delta.x)) { if (Mathf.Atan(Mathf.Abs(delta.y) / Mathf.Abs(delta.x)) > Mathf.Deg2Rad * 70) { SetDragType(DragType.DragScroll); } else { SetDragType(DragType.DragSelf); } } } switch (dragType) { case DragType.DragScroll: scrollRect.OnDrag(eventData); break; case DragType.DragSelf: transform.position += (Vector3)eventData.delta; break; } } private void EndDrag(PointerEventData eventData) { scrollRect.OnEndDrag(eventData); SetDragType(DragType.None); totalDelta = Vector3.zero; } }