当前位置: 代码迷 >> 综合 >> UGUI ScrollRect 有按钮时设置拖拽
  详细解决方案

UGUI ScrollRect 有按钮时设置拖拽

热度:58   发布时间:2023-12-15 17:26:13.0

using UnityEngine;
using System.Collections.Generic;

//在scrollrect控件 下的content控件上添加
public class ScrollDragHelper : MonoBehaviour {

    public List<GameObject> ChildObjectList = new List<GameObject>();

    private void Awake()
    {
        if (ChildObjectList.Count > 0)
        {
            for (int index = 0; index < ChildObjectList.Count; index++)
            {
                ChildObjectList[index].AddComponent<ScrollDrag>();
            }
        }
        else
        {
            GameObject childobj = null;
            for (int index = 0; index < gameObject.transform.childCount; index++)
            {
                childobj = gameObject.transform.GetChild(index).gameObject;
                childobj.AddComponent<ScrollDrag>();
                ChildObjectList.Add(childobj);
            }
        }
    }
}

using System.Collections;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using System.Collections.Generic;
using System;
 

//使用ScrollDragHelper脚本,自动在 ScrollRect控件下的Content控件的子控件button上添加ScrollDrag脚本,或者手动在button上添加ScrollDrag脚本
public class ScrollDrag : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler
{
    private ScrollRect scroll_rect;
    private Image raycast_Image;

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

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

    public void OnBeginDrag(PointerEventData eventData)
    {
        if (scroll_rect)
        {
            scroll_rect.OnBeginDrag(eventData);
        }
        if (raycast_Image)
        {
            raycast_Image.raycastTarget = false;
        }
    }

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

    public void OnEndDrag(PointerEventData eventData)
    {
        if (scroll_rect)
        {
            scroll_rect.OnEndDrag(eventData);
        }
        if (raycast_Image)
        {
            raycast_Image.raycastTarget = true;
        }
    }
}