Ben I.
Ben I.

Reputation: 1082

GameObject disappears during OnDrag

I have an inventory system based largely on this tutorial that I am currently in the process of modifying. OnBeginDrag and OnEndDrag work as expected, but OnDrag, though continuously updating the position of the item, does not display the item. It disappears during OnDrag, and reappears once it has been dropped in its new slot.

Here is my hierarchy:

Unity hierarchy

Of note are the two cameras. The DungeonGroup (and the DungeonUICanvas) use DungeonCamera as far as I can tell. (DungeonGroup was, until recently, a completely different Scene. The OnDrag worked as expected before I integrated the scenes, making me think that a camera issue could be the culprit.)

Here is the code I am currently working with:

public class DragHandler : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler
{
    public static GameObject item; //itemBeingDragged
    public static Vector3 startPosition;
    public static Transform startParent;

    public void OnBeginDrag(PointerEventData eventData)
    {
        item = gameObject;
        startPosition = transform.position;
        startParent = transform.parent;

        GetComponent<CanvasGroup>().blocksRaycasts = false;

        transform.SetParent(transform.root);
    }

    public void OnDrag(PointerEventData eventData)
    {
        transform.position = Input.mousePosition;
    }

    public void OnEndDrag(PointerEventData eventData)
    {
        item = null;

        if (transform.parent == startParent || transform.parent == transform.root)
        {
            transform.position = startPosition;
            transform.SetParent(startParent);
        }

        GetComponent<CanvasGroup>().blocksRaycasts = true;
    }
}

Upvotes: 0

Views: 979

Answers (1)

Erik Overflow
Erik Overflow

Reputation: 2306

Canvas works a little differently than WorldSpace objects. From Unity's UICanvas documentation it states:

UI elements in the Canvas are drawn in the same order they appear in the Hierarchy. The first child is drawn first, the second child next, and so on. If two UI elements overlap, the later one will appear on top of the earlier one.

When you move your transform to root, you are moving the object up higher in the UI hierarchy, resulting in it being "drawn first". Since it's drawn first, all other elements are drawn in front of it, making it "disappear". My recommendation is to .SetParent to a transparent UI gameObject further down in your hierarchy, rather than the root.

Upvotes: 1

Related Questions