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

UGUI ScrollRect 带按钮的拖拽

热度:69   发布时间:2023-12-15 17:26:53.0

UGUI 当ScrollRect的Content带有按钮的时候,当拖拽位置在按钮上的时候,按钮的点击会遮挡scrllrect的拖动。这是使用这个脚本就能解决问题。在按钮的父节点上添加这个脚本。(或者可以将button换成toggle,toggle支持滑动)

 

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;
        }
    }
}