How do I change the sorting layer of a UI image when it is being dragged?

I’m creating an inventory system, and am currently working on the UI display for it. However, I’m running into an issue in which implementing IDragHandler and dragging a UI image during play mode causes the image to appear behind other UI elements.

I understand that the way the Canvas sorts UI objects is from the top down, so that game objects at the bottom of the canvas hierarchy appear in front of objects that come earlier. My hierarchy looks like this:



++++Slot Container

++++++Slot 1 (has a simple UI script with IDragHandler)

++++++++Item Image

++++++Slot 2 (has a simple UI script with IDragHandler)

++++++++Item Image

My slot UI script detects dragging, and then moves the slots’ items to the location of my cursor when dragged. The only issue is that Slot 1’s Item Image appears behind the entirety of Slot 2 when dragged near it; Slot 2’s Item Image does not have this issue because it’s lower in the hierarchy, and hence sorted in a higher layer.

How do I fix this? I would find it to be a pain if I had to create some jumbled hierarchy structure just to fix what seems to be a simple issue, and yet I am not aware of a good solution. To be clear, my desired behavior is to simply have any dragged item be visible above the entire inventory.

If your objects never overlap, there is a quick fix with almost no additional overhead: transform.SetAsLastSibling

If your click-and-drag code is attached directly to the transform of your Slot 1 or Slot 2 object, it should look like this:

void IBeginDragHandler.OnBeginDrag(PointerEventData eventData)

If you aren’t using the hierarchy of items inside Slot Container to do anything else code-wise, this will move whatever Slot you click on to the “front” of your UI by putting it at the “end” of your hierarchy.

Fantastic. It also solved my problem. Thank you very much for sharing the solution.