드래그 마우스 입력에 반응하는 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()
{
}
}
}
'Unity > 정보' 카테고리의 다른 글
[Unity] 경량화된 notosans 폰트 (0) | 2023.05.09 |
---|---|
[Unity] 사용자 커스텀 마우스 커서 적용 (0) | 2023.04.25 |
[Unity] apk 용량 경량화 방법들 (0) | 2023.04.21 |
[Unity] 아바타 마스크를 이용해서 부위별로 방향 분리 하는 방법 (0) | 2023.04.21 |
[Unity] 스크롤바 UI Prefab (0) | 2023.04.20 |