关于ScrollView拖拽事件和Button点击事件冲突解决方法

将脚本挂载在ScrollView结构下需要响应时间的对象上

using UnityEngine.UI;
using UnityEngine.EventSystems;
using UnityEngine;

public class GDragEventDispatcher : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler
{

    ScrollRect anotherScrollRect;

    private Image thisRaycast;

    void Awake()
    {
        //FindScrollRect(gameObject);
        //if (anotherScrollRect)
        //{
        //    thisRaycast = gameObject.GetComponent();
        //}
    }
    void Start()
    {
        FindScrollRect(gameObject);
        if (anotherScrollRect)
        {
            thisRaycast = gameObject.GetComponent();
        }
    }

    private void FindScrollRect(GameObject obj)
    {
        GameObject tempObj = obj.transform.parent.gameObject;
        //Debug.Log("测试"+tempObj.gameObject.name);
        anotherScrollRect = tempObj.GetComponent();
        if (anotherScrollRect)
        {
            //Debug.Log(anotherScrollRect.gameObject.name);
            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;
        }
    }
}


你可能感兴趣的:(C#,Unity3D)