I was trying to make a game where a player can drag and drop options to a slot. Both the slot and the draggable objects have public int ID. Instead of instantly checking if the ID of the slot matches the ID of the drag object upon dropping, I’d like it to be done on the onclick event of a ui button. Meaning, options can be dragged and dropped on the slot regardless if the IDs are a match.
How should I do this? (I was thinking of making a new method in the slot cs or making a new cs for the checking and attach it to ui button, however, i don’t know how to construct it or reference the id). I’m still new to all of these so any advice will be a big help. Thanks in advance!
Cs of the draggable object/s
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.EventSystems; public class DragAndDrop : MonoBehaviour, IPointerDownHandler, IBeginDragHandler, IEndDragHandler, IDragHandler { private RectTransform rectTrans; public Canvas myCanvas; private CanvasGroup canvasGroup; public int id; private Vector2 initPos; private void Start() { rectTrans = GetComponent<RectTransform>(); canvasGroup = GetComponent<CanvasGroup>(); initPos = transform.position; } public void OnBeginDrag(PointerEventData eventData) { canvasGroup.blocksRaycasts = false; } public void OnDrag(PointerEventData eventData) { rectTrans.anchoredPosition += eventData.delta/ myCanvas.scaleFactor; } public void OnEndDrag(PointerEventData eventData) { canvasGroup.blocksRaycasts = true; } public void OnPointerDown(PointerEventData eventData) { } public void ResetPosition() { transform.position = initPos; } }
Cs of the slot/s
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.EventSystems; public class SlotScript : MonoBehaviour, IDropHandler { public int id; public void OnDrop(PointerEventData eventData) { if (eventData.pointerDrag != null) { if (eventData.pointerDrag.GetComponent<DragAndDrop>().id == id) { Debug.Log(“Correct”); eventData.pointerDrag.GetComponent<RectTransform>().anchoredPosition = this.GetComponent<RectTransform>().anchoredPosition; } else { Debug.Log(“Wrong”); eventData.pointerDrag.GetComponent<DragAndDrop>().ResetPosition(); } } } }