Drag-and-drop match game system

Tyler Smallwood
4 min readOct 13, 2023

--

Objective: Set up a system to make a drag and drop matching game.

Based off the last article I’ve written, I will expand a little on it to make sure the items match their specific location.

For this project, the scene will need three images to act like holders, three TextMeshPro text objects to name the slots, and three more images to act like the items.

Create a Drag and Drop script. Starting with Drag, we will grab UnityEngine.UI and EventSystems library’s as well as implement IDragHandler, IBeginDragHandler, and IEndDragHandler.

Create a Vector3 variable to hold the items starting position and a reference to the Image component.

In start use Getcomponent to grab the Image component and set the _startPOS to equal the items transform.position.

Create a public method that will reset the images position if it’s not on a slot. Since this is an Image that is being dragged, use the image’s rectTransform.localPosition.

In OnDrag method set transform.position to eventData.position.

In OnBeginDrag, change the image’s alpha and set raycastTarget to false.

In OnEndDrag, this will be different than the last article. The first thing is to call the ResetPosition method. After this it’s the same. Set the alpha of the image back to 1 and reactive the raycastTarget.

Add this script to the items.

Onto the drop script. In here we need to grab the UI and EventSystems and implement the IDropHandler interface. We will need a string variable to check the tag of the item being drop. And a reference to the image component.

In start grab the component.

In the OnDrop method, we will check the pointerDrag’s tag. If it is the right tag, grab a reference to the Drag script and set the _startPos to equal the slot’s image rectTransform.localPosition.

Save the script and in Unity add it to all three slots. Before setting the itemType, go to the top of inspector, under the objects name and create three new tags. For this project, I created Lighting, Spell, and Bomb.

Go through each slot and add in one of the new tags.

Next go through the items and set their tags.

And just like that, the items have their right home and can’t be dropped in another slot. This was a good way to use the Supported Event Systems to make a simple game.

Thank you for reading! Have a wonderful day!

--

--

Tyler Smallwood
Tyler Smallwood

Written by Tyler Smallwood

I am passonate on learning to program and use Unity to become a skillful Unity Developer

No responses yet