68 lines
2.0 KiB
C#
68 lines
2.0 KiB
C#
|
|
using UnityEngine;
|
||
|
|
using UnityEngine.UI;
|
||
|
|
using UnityEngine.EventSystems;
|
||
|
|
|
||
|
|
public class InventoryItemUI : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler, IPointerClickHandler
|
||
|
|
{
|
||
|
|
private Item item;
|
||
|
|
private int quantity;
|
||
|
|
private InventoryUI inventoryUI;
|
||
|
|
private Image itemImage;
|
||
|
|
private Text quantityText;
|
||
|
|
private Canvas canvas;
|
||
|
|
private GraphicRaycaster raycaster;
|
||
|
|
private CanvasGroup canvasGroup;
|
||
|
|
|
||
|
|
public void Initialize(Item newItem, int qty, InventoryUI ui)
|
||
|
|
{
|
||
|
|
item = newItem;
|
||
|
|
quantity = qty;
|
||
|
|
inventoryUI = ui;
|
||
|
|
|
||
|
|
itemImage = GetComponent<Image>();
|
||
|
|
quantityText = GetComponentInChildren<Text>();
|
||
|
|
canvas = GetComponentInParent<Canvas>();
|
||
|
|
canvasGroup = GetComponent<CanvasGroup>();
|
||
|
|
|
||
|
|
if (itemImage != null && item.itemIcon != null)
|
||
|
|
itemImage.sprite = item.itemIcon;
|
||
|
|
|
||
|
|
if (quantityText != null)
|
||
|
|
quantityText.text = quantity > 1 ? quantity.ToString() : "";
|
||
|
|
|
||
|
|
// Make draggable
|
||
|
|
if (canvasGroup == null)
|
||
|
|
canvasGroup = gameObject.AddComponent<CanvasGroup>();
|
||
|
|
|
||
|
|
GetComponent<RectTransform>().sizeDelta = new Vector2(64, 64);
|
||
|
|
}
|
||
|
|
|
||
|
|
public void OnBeginDrag(PointerEventData eventData)
|
||
|
|
{
|
||
|
|
canvasGroup.alpha = 0.6f;
|
||
|
|
canvasGroup.blocksRaycasts = false;
|
||
|
|
}
|
||
|
|
|
||
|
|
public void OnDrag(PointerEventData eventData)
|
||
|
|
{
|
||
|
|
GetComponent<RectTransform>().anchoredPosition += eventData.delta / canvas.scaleFactor;
|
||
|
|
}
|
||
|
|
|
||
|
|
public void OnEndDrag(PointerEventData eventData)
|
||
|
|
{
|
||
|
|
canvasGroup.alpha = 1f;
|
||
|
|
canvasGroup.blocksRaycasts = true;
|
||
|
|
|
||
|
|
// Reset position on drop (TODO: check if dropped on equip slot)
|
||
|
|
GetComponent<RectTransform>().anchoredPosition = Vector2.zero;
|
||
|
|
}
|
||
|
|
|
||
|
|
public void OnPointerClick(PointerEventData eventData)
|
||
|
|
{
|
||
|
|
if (eventData.button == PointerEventData.InputButton.Right)
|
||
|
|
{
|
||
|
|
inventoryUI.ShowContextMenu(this, item);
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|