반응형
유니티 C# 인벤토리 드래그 앤 드롭 시스템 간단 구현 Inventory Drag and Drop
InventorySlot.cs 작성
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
public class InventorySlot : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler, IPointerClickHandler, IPointerEnterHandler, IPointerExitHandler
{
private Transform originalParent;
private CanvasGroup canvasGroup;
private RectTransform rectTransform;
public Item item;
private float lastClickTime;
private const float doubleClickTime = 0.3f;
private void Awake()
{
canvasGroup = GetComponent<CanvasGroup>();
rectTransform = GetComponent<RectTransform>();
}
public void OnBeginDrag(PointerEventData eventData)
{
originalParent = transform.parent;
transform.SetParent(transform.root);
canvasGroup.blocksRaycasts = false;
canvasGroup.alpha = 0.6f;
}
public void OnDrag(PointerEventData eventData)
{
rectTransform.anchoredPosition += eventData.delta;
}
public void OnEndDrag(PointerEventData eventData)
{
transform.SetParent(originalParent);
canvasGroup.blocksRaycasts = true;
canvasGroup.alpha = 1f;
// 드롭한 대상이 인벤토리 슬롯인지 확인
if (eventData.pointerEnter != null && eventData.pointerEnter.GetComponent<InventorySlot>() != null)
{
InventorySlot targetSlot = eventData.pointerEnter.GetComponent<InventorySlot>();
SwapItems(targetSlot);
}
rectTransform.anchoredPosition = Vector3.zero;
}
void SwapItems(InventorySlot targetSlot)
{
Item tempItem = targetSlot.item;
targetSlot.item = this.item;
this.item = tempItem;
UpdateSlotUI();
targetSlot.UpdateSlotUI();
}
public void UpdateSlotUI()
{
if (item != null)
{
GetComponentInChildren<Image>().sprite = item.itemIcon;
GetComponentInChildren<Image>().enabled = true;
}
else
{
GetComponentInChildren<Image>().enabled = false;
}
}
}
반응형