- Home /
Check to see if item is in correct slot
I'm making a game where players have to drag letters into the correct slot to solve an anagram puzzle.
I have 2 components: the letter (which is a UI Image) and a slot (also a UI Image)
The letter has this script on it which handles the drag and drop:
[SerializeField] private Canvas canvas;
private RectTransform rectTransform;
private CanvasGroup canvasGroup;
private void Awake(){
rectTransform = GetComponent<RectTransform>();
canvasGroup = GetComponent<CanvasGroup>();
}
public void OnBeginDrag(PointerEventData eventData){
canvasGroup.alpha = .6f;
canvasGroup.blocksRaycasts = false;
}
public void OnDrag(PointerEventData eventData){
rectTransform.anchoredPosition += eventData.delta/ canvas.scaleFactor;
}
public void OnEndDrag(PointerEventData eventData){
canvasGroup.alpha = 1f;
canvasGroup.blocksRaycasts = true;
}
public void OnPointerDown(PointerEventData eventData){
}
And the slot has this script, which is meant to make the letter snap to the slot:
public void OnDrop (PointerEventData eventData){
Debug.Log ("OnDrop");
if (eventData.pointerDrag !=null){
eventData.pointerDrag.GetComponent<RectTransform>().anchoredPosition = GetComponent<RectTransform>().anchoredPosition;
}
}
Once the player has dragged all the letters into slots, they press a 'Submit' button. At this point I want to check that the correct letter is in the correct slot (i.e. Slot 1 should contain Letter A).
How would I go about this?
Answer by pauldarius98 · Mar 02, 2021 at 01:07 PM
Create a letter class that derives from MonoBehaviour and has an Id (and any other information that you might need) and add it to your draggable letter
public class Letter : MonoBehaviour
{
public string Id;
}
Then in your Slot script add 1 field for the Id (public string Id), one private field droppedId and a method IsCorrect like below:
public class Slot : MonoBehaviour, IDropHandler
{
public string Id;
private string droppedItemId = string.Empty;
public bool IsCorrect
{
return Id == droppedItemId;
}
public void OnDrop (PointerEventData eventData){
Debug.Log ("OnDrop");
if (eventData.pointerDrag !=null){
eventData.pointerDrag.GetComponent<RectTransform>().anchoredPosition = GetComponent<RectTransform>().anchoredPosition;
var letter = eventData.pointerDrag.GetComponent<Letter>();
if (letter != null)
{
droppedItemId = letter.Id;
}
else
{
Debug.LogError("There was no letter attached to the dropped item!");
}
}
}
}
Now you can check for each slot if the item dropped is the right one by using slot.IsCorrect, just make sure to assign the right ids for letters and slots