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?

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.

Hi, I have the same problem and I’ve tried to set the canvas as the parent of the dragged object, but it breaks the entire drag & drop system.
Do you have any suggestions? Let me know if you need further information.