Making a drag-and-drop item system

Suleiman Abdullah
3 min readSep 8

--

Objective: Making a drag-and-drop item system.

I have prepared my scene with 3 Images.

Create a new script called Drop and attach it to these 3 Images.

To Drag this Item we need to add IDragHandler and then implement its base function called OnDrag.

When we drag the Object we need to make sure it snaps to the object center of the Input Pointer which is a mouse position for this one, to get the mouse position we use PointerEventData here it is renamed eventData

In this step, I want to add two Images in the hierarchy called Itemslot, then create a new script and attach it to them.

Now re-order the Item_Slot in the upper position to the item, because, if the item is below the item_Slot the item will be rendered behind.

Note: You can do this using the order layer on the image to get the same result even if the slot is below the image.

Open the ItemSlot script and Implement the IDropHandler interface, OnDrop - Called on the object where a drag finishes

Now we will use eventDate.pointerDrag, which will be the object that has an OnDrag but finished dragged. But here we want to center that object with the slot.

Now we will have a problem we won't be able to detect the OnDrop event, To solve this we need to disable the item option called raycastTarget when we drag the item on the Drop scrip. But to do this we need to implement an Interface called IBeginDragHandler, get the image component then disable the raycastTarget.

But If we turn off the rayCastTarget when we finish dragging, we won't be able to drag that object again, to be able to drag that object we need to turn it off when we finish the OnDrop action, we do this by implementing IEndDragHandler on Drop script.

Bonus I will make the Item reduce transparency when begins dragging and reset its transparency when ends dragging.

This is how to make a drag-and-drop Item system.

--

--

Suleiman Abdullah

Self taught Unity Developer, who is passion about making games ,and he loves Math For Game Development