using TMPro; using UnityEngine; using UnityEngine.EventSystems; using UnityEngine.UI; // Drag Dropable public class ItemHandler : MonoBehaviour, IPointerDownHandler, IBeginDragHandler, IEndDragHandler, IDragHandler { [SerializeField] private Canvas canvas; private CanvasGroup _canvasGroup; private Canvas _dragLayerCanvas; private Transform _originalParent; private Vector2 _originalPosition; private RectTransform _rectTransform; private void Awake() { _rectTransform = GetComponent(); _canvasGroup = GetComponent(); if (_canvasGroup == null) _canvasGroup = gameObject.AddComponent(); if (canvas == null) canvas = GameObject.Find("UICanvas").GetComponent(); _dragLayerCanvas = GameObject.Find("DragLayerCanvas").GetComponent(); } public void OnBeginDrag(PointerEventData eventData) { // starting slot type and slot index var parentSlotComponent = eventData.pointerDrag.GetComponentInParent(); Debug.Log("Parent Slot Type: " + parentSlotComponent.GetSlotType()); Debug.Log("Begin Drag"); _originalPosition = _rectTransform.anchoredPosition; _canvasGroup.alpha = 0.6f; _canvasGroup.blocksRaycasts = false; _canvasGroup.interactable = false; // Disable interaction while dragging } public void OnDrag(PointerEventData eventData) { // Ensure the canvas is set if (canvas == null) { Debug.LogWarning("Canvas is null"); return; } // Convert the mouse position to world position var gameCamera = GameObject.Find("Main Camera").GetComponent(); var worldPosition = gameCamera.ScreenToWorldPoint(eventData.position); worldPosition.z = 0f; // Set z-coordinate to 0 to ensure the item stays on the UI plane // Update the item's position to follow the mouse _rectTransform.position = worldPosition; } public void OnEndDrag(PointerEventData eventData) { Debug.Log("End Drag"); var parentSlotComponent = eventData.pointerDrag.GetComponentInParent(); // Check if dropped on a valid slot var hitObjects = eventData.hovered; var droppedOnValidSlot = false; foreach (var obj in hitObjects) if (obj.GetComponent() != null && obj.GetComponent() != parentSlotComponent) { droppedOnValidSlot = true; break; } // if its the same slot then retur to last position if (!droppedOnValidSlot) // Snap back to original position if not dropped in a valid slot _rectTransform.anchoredPosition = _originalPosition; _canvasGroup.alpha = 1.0f; _canvasGroup.blocksRaycasts = true; _canvasGroup.interactable = true; // Enable interaction after dragging } public void OnPointerDown(PointerEventData eventData) { Debug.Log("OnPointerDown"); } public void DisplayItem(GameItem item) { if (item == null) { Debug.Log("Item is null!"); Destroy(transform.gameObject); return; } // Debug.Log(transform.GetChild(1)); transform.Find("ItemName").GetComponent().text = item.name; transform.Find("qty").GetComponent().text = item.quantity; transform.Find("Icon").GetComponent().sprite = item.icon; Debug.Log("completed processing set item"); } }