Making a drag-and-drop item system

Tyler Smallwood
3 min readOct 12, 2023

--

Objective: Create a Drag and drop system with UI.

This project will need a background Image, an Image to act like a holder, and three more images to be draggable.

We will need two scripts, one will go on the items to allow them to be dragged and another will allow the item to snap the item. For this article, the two I created are named Draggable and Droppable.

Starting with Draggable, this script will need the UnityEngine.EventSystems and UI library’s. After grabbing the library’s, the script will need to Inherent the IDragHandler, IBeginDragHander, and IEndDragHandler.

Make sure to implement these interfaces.

In OnDrag, set the transfom.position to equal the eventData.positon. This will allow the item to be dragged by the mouse and move with the mouse.

The reason OnBeginDrag and OnEndDrag are there is to make the item a little less opaque and to turn off the images raycasttarget. To do this grab a reference to the image component. In start use getcomponent to attach the reference to the Component. Don’t forget to Null check it.

Now in OnBeginDrag, create a temporary variable to hold the image’s color. Then set the alpha of temp to .5f to half the alpha. To finalize the select look, set the image.color to equal the temp variable. Finishing up OnBehinDrag set the _image.raycastTarget to false.

To finish up the draggables, just undo everything that was just done in OnEndDrag. Set the image’s alpha back to 1 and raycastTarget to true.

Drop this script onto each of the items.

On to droppable. In this script, just grab UnityEngine.EventSystems again and implement the IDropHandler interface. In the OnDrop, we can grab the dragged objects information by using eventData.pointerDrag. Using just this, everything on that object can be grabbed, transform, getcomponent, name, or tag. Grab it’s transform.position and set it to the slots transform.position.

Drop this script onto the slot Image.

With that our items can be grabbed and will snap to the slots position.

Thanks 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