Unity/정보

[Unity] UI 드래그 이동

달시_Dalsi 2023. 4. 20. 03:12

드래그 마우스 입력에 반응하는 UI를 'Drag Rect transform'에 넣어주면 작동한다.

 

 

using UnityEngine;
using UnityEngine.Events;
using UnityEngine.EventSystems;

public class DraggableUI : UIBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler
{
    public RectTransform dragRectTransform;

    private Canvas m_Canvas;
    public Canvas canvas
    {
        get
        {
            if (m_Canvas == null)
            {
                m_Canvas = GetComponentInParent<Canvas>();
            }
            return m_Canvas;
        }
    }

    protected override void OnEnable()
    {
        if (dragRectTransform == null)
        {
            dragRectTransform = gameObject.GetComponent<RectTransform>();
        }

        if (dragRectTransform == null || canvas == null)
        {
            enabled = false;
        }

        onDrag.AddListener(OnDragMove);
    }

    protected override void OnDisable()
    {
        onDrag.RemoveListener(OnDragMove);
    }

    public void OnDragMove(PointerEventData eventData)
    {
        dragRectTransform.anchoredPosition += eventData.delta / canvas.scaleFactor;
    }

    protected override void OnCanvasHierarchyChanged()
    {
        m_Canvas = GetComponentInParent<Canvas>();
    }

    public DragEvent onBeginDrag = new DragEvent();
    public DragEvent onDrag = new DragEvent();
    public DragEvent onEndDrag = new DragEvent();

    public void OnBeginDrag(PointerEventData eventData)
    {
        onBeginDrag.Invoke(eventData);
    }

    public void OnDrag(PointerEventData eventData)
    {
        onDrag.Invoke(eventData);
    }

    public void OnEndDrag(PointerEventData eventData)
    {
        onEndDrag.Invoke(eventData);
    }

    [System.Serializable]
    public class DragEvent : UnityEvent<PointerEventData>
    {
        public DragEvent()
        {

        }
    }
}

DraggableUI.cs
0.00MB