- Home /
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:
Canvas
++Inventory
++++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.
Answer by johnathonjcramer · Feb 03, 2020 at 07:50 PM
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)
{
transform.SetAsLastSibling();
}
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.
Answer by Gervagared · Apr 22 at 07:40 PM
Fantastic. It also solved my problem. Thank you very much for sharing the solution.
Your answer
![](https://koobas.hobune.stream/wayback/20220612201923im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
UI object drawing order is different between Unity Editor and Standalone version 1 Answer
Flickering Image whith different resolution 0 Answers
Unity 4.6 UI How to put a sprite between two UI Images? 0 Answers
Issues rotating a UI image while the canvas is parented to the Main Camera 0 Answers
How change the camera orthographic size to the UI image top position? 1 Answer