In this article we’ll implement a quick and dirty drag and drop item to slot system with Unity’s built-in UI system.
For this project, our Canvas will have two child images named “Slot_1” and “Slot_2”, an empty element named “Items” with the Horizontal Layout Group component attached, and seven child images labeled “Item_#”.
We’ll be making all of the Item image elements draggable onto the Slot image elements.
Create a new script and attach it to each Item element.
In the script, add the interfaces shown above and then implement their missing members (in Rider, similar in Visual Studio).
The DragItem Class/Script
We’ll start with just two class variables to hold the item’s Image and a color to shade the Image when it is being dragged.
We’ll use Unity’s UI draggable interfaces to change the color of the item when it is being dragged and to set it back to normal when it’s not being dragged.
On the Drag Item script component for each Item Image element, set the color to pure white with an alpha around half the max.
Create a new script named “DropItem” and add it to each of the Slot elements.
The DropItem Class/Script
On the DropItem script, add the “IDropHandler” interface and its associated members as shown above.
There isn’t much to this script, basically we want to grab the pointerDrag information which has the item Image element when it is being dragged and set the position to our droppable slot Image element’s position.
One Necessary Tweak to the DragItem Class/Script
For our slot Image element to be raycast targetable when dragging the item Image element, we need to disable the item Image element as a raycast target.
Hit play and the slots should work correctly.
Making the Items Element Droppable
We can also make the Items element a droppable slot by assigning it the DropItem script as a component and adding the Image component which gives it a raycast target.
Set the color’s alpha to 0 so that it has no background.
Unparenting in the DragItem Class/Script
For the Horizontal Layout Group on the Items element to work properly, we need the Items to unparent when they are repositioned outside of it.
We still need to parent to the canvas or the background image of the canvas.
Setting the parent to null will just cause issues.
Parenting in the DropItem Class/Script
When we drop an Item into a slot, we want to parent it to that slot as well.
Hit play and enjoy the drag and drop functionality!