1. 程式人生 > >unity3dScrollRect與OnDrag事件的衝突解決方法

unity3dScrollRect與OnDrag事件的衝突解決方法

借鑑  https://www.jianshu.com/p/8bfe94822886

using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
/// <summary>
/// 指令碼掛載到每個可拖拽的Item上面即可
/// </summary>
public class ItemOnDrag : MonoBehaviour, IPointerDownHandler, IPointerUpHandler, IBeginDragHandler, IDragHandler, IEndDragHandler
{
    
// 例項化的新item public GameObject mNewItem; public Transform mNewItemRoot; public ScrollRect mScrollRect; // 是否按下 public bool mIsDown = false; // 按下與鬆開滑鼠之間的距離 public float mBorderDis = 0.5f; // 總的按下時間 public float mTotalTime = 1; private float mCurTime = 0; // 當前滑鼠位置 public
Vector3 mCurPos; // 上一次滑鼠位置 public Vector3 mPrevPos; private NewItemOnDrag mNewDrag; void Start() { mNewItemRoot = GameObject.Find("InfoBoard").transform; mScrollRect = GameObject.Find("InfoBoard").GetComponent<ScrollRect>(); } void Update() {
if (mScrollRect == null) { } if (mIsDown) { mCurTime += Time.deltaTime * 1; if (mCurTime >= mTotalTime) { if (Vector3.Distance(mPrevPos, mCurPos) > mBorderDis) { mCurTime = 0f; return; } mCurTime = 0f; mIsDown = false; GameObject item = Instantiate(mNewItem); item.transform.SetParent(mNewItemRoot); item.transform.localScale = Vector3.one; mNewDrag = item.GetComponent<NewItemOnDrag>(); if (mNewDrag == null) mNewDrag = item.AddComponent<NewItemOnDrag>(); item.transform.position = Input.mousePosition; } } } public void OnPointerDown(PointerEventData eventData) { mNewDrag = null; mPrevPos = Input.mousePosition; mCurPos = Input.mousePosition; mIsDown = true; } public void OnPointerUp(PointerEventData eventData) { mPrevPos = Vector3.zero; mCurPos = Vector3.zero; mIsDown = false; mNewDrag = null; } public void OnBeginDrag(PointerEventData eventData) { mScrollRect.OnBeginDrag(eventData); } public void OnDrag(PointerEventData eventData) { mCurPos = eventData.position; if (mNewDrag == null) mScrollRect.OnDrag(eventData); else mNewDrag.transform.position = Input.mousePosition; } public void OnEndDrag(PointerEventData eventData) { mNewDrag = null; mScrollRect.OnEndDrag(eventData); } }

 

using UnityEngine;
using UnityEngine.EventSystems;

public class NewItemOnDrag : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler
{
    public void OnBeginDrag(PointerEventData eventData)
    {

    }

    public void OnDrag(PointerEventData eventData)
    {
        transform.position = Input.mousePosition;
    }

    public void OnEndDrag(PointerEventData eventData)
    {

    }
}

 

用法

將ItemOnDrag掛在每個可拖拽的Item上面即可
  其中的mNewItem就是Item本身的預設體,mNewItemRoot是ScrollRect元件容器的transform,mScrollRect是ScrollRect元件容器的ScrollRect,但是mNewItemRoot和mScrollRect需要手動關聯

NewItemOnDrag指令碼會自動掛載到新例項化出來的item上的,不要做處理,後期可加入檢測