- Home /
Drag and Drop problem with order of UI items (behind others)
I have followed this tutorial Unity UI Drag and Drop Tutorial. It works fine, however the dragged object might get behind others due to the UI sorting behavior.
I have tried to add the Canvas component to override the sorting - unfortunately this leads to inability to drag the object.
Another approach is to sort the elements in hierarchy (for example with Transform.SetAsLastSibling). This solves the issue with elements being behind, however reorders the slots every time user drags an item.
How can I solve the problem?
Answer by dreamwagon · Nov 09, 2016 at 08:30 AM
Read the comments of that tutorial and find the one by Clint Willard. The solution is to make the image a child of a canvas when it is being dragged (or create a top level canvas in my case, I had multiple canvases).
Here is the class. copied from those comments.
public class ItemDragHandler : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler {
public static GameObject itemBeingDragged;
Vector3 startPosition;
Transform startParent;
Transform canvas;
public void OnBeginDrag(PointerEventData eventData) {
itemBeingDragged = gameObject;
startPosition = transform.position;
startParent = transform.parent;
GetComponent<CanvasGroup>().blocksRaycasts = false;
canvas = GameObject.FindGameObjectWithTag("UI Canvas").transform;
transform.parent = canvas;
}
public void OnDrag(PointerEventData eventData) {
transform.position = Input.mousePosition;
}
public void OnEndDrag(PointerEventData eventData) {
Debug.Log(transform.parent + " == " + canvas);
itemBeingDragged = null;
GetComponent<CanvasGroup>().blocksRaycasts = true;
if (transform.parent == canvas) {
transform.position = startPosition;
transform.parent = startParent;
}
}
}
Note: If you have multiple canvases, you will need to set the one with the draggable item to a higher sort order than the one containing the slots.
Your answer
Follow this Question
Related Questions
What sets Canvas.renderOrder and why would it not respect the sorting order? 0 Answers
[4.6 - UI] Force GUI to render on top 1 Answer
How to change UI image render order dynamically on runtime 1 Answer
Conditionals in UI Drag and Drop? 2 Answers
How to do a raycast between an UI Element and Sprite 2D? 0 Answers