Unity ScrollView拖动和Button等触发事件冲突解决

此脚本挂在ScrollView下具有触发事件检测的物体上:

using UnityEngine.UI;
using UnityEngine.EventSystems;
using UnityEngine;
public class DragElement : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler
{

    ScrollRect anotherScrollRect;
    private Image thisRaycast;

    void Start()
    {
        FindScrollRect(gameObject);
        if (anotherScrollRect)
        {
            thisRaycast = gameObject.GetComponent<Image>();
        }
    }

    private void FindScrollRect(GameObject obj)
    {
        GameObject tempObj = obj.transform.parent.gameObject;
        anotherScrollRect = tempObj.GetComponent<ScrollRect>();
        if (anotherScrollRect)
        {
            return;
        }
        else
        {
            FindScrollRect(tempObj);
        }
    }

    public void OnBeginDrag(PointerEventData eventData)
    {
        if (anotherScrollRect)
        {
            anotherScrollRect.OnBeginDrag(eventData);
        }
        if (thisRaycast)
        {
            thisRaycast.raycastTarget = false;
        }
    }

    public void OnDrag(PointerEventData eventData)
    {
        if (anotherScrollRect)
        {
            anotherScrollRect.OnDrag(eventData);
        }
    }

    public void OnEndDrag(PointerEventData eventData)
    {
        if (anotherScrollRect)
        {
            anotherScrollRect.OnEndDrag(eventData);
        }
        if (thisRaycast)
        {
            thisRaycast.raycastTarget = true;
        }
    }
}

原文:关于ScrollView拖拽事件和Button点击事件冲突解决方法_愚公丨Acmen的博客-CSDN博客

猜你喜欢

转载自blog.csdn.net/weixin_42565127/article/details/126521679