Parent Order Bug in DragItem

There is currently a bug that the sibling index does not get restored. In my game, I have a mouseover overlay as well as a press overlay. If you drag the item “Icon”, after dropping it will get moved to on top of the overlays. This means that when you are using the drag system, the order of you UI elements can change.

Item Slot
-Border (image)
-Icon (image)
-Hover Overlay (image)
-Press Overlay (image)

Here is the fix that needs to be applied to the class DragItem:

First, add a new private int at the top of the class to store the sibling index:

private int _originalSiblingIndex;

Next, update the void IBeginDragHandler.OnBeginDrag(PointerEventData eventData) method:

void IBeginDragHandler.OnBeginDrag(PointerEventData eventData) {
    _startPosition = transform.position;
    _originalParent = transform.parent;
    _originalSiblingIndex = transform.GetSiblingIndex();
    // Else won't get the drop event.
    GetComponent<CanvasGroup>().blocksRaycasts = false;
    transform.SetParent(_parentCanvas.transform, true);
}

Last, modify the void IEndDragHandler.OnEndDrag(PointerEventData eventData) method:

void IEndDragHandler.OnEndDrag(PointerEventData eventData) {
    transform.position = _startPosition;
    GetComponent<CanvasGroup>().blocksRaycasts = true;
    transform.SetParent(_originalParent, true);
    transform.SetSiblingIndex(_originalSiblingIndex);
    var container = !EventSystem.current.IsPointerOverGameObject() ? 
        _parentCanvas.GetComponent<IDragDestination<T>>() : GetContainer(eventData);
     if (container != null) DropItemIntoContainer(container);
 }

After this change, the sibling index will be restored.

Please note that in my script I have changed the instance variable names
_startPosition => startPosition
_originalParent => originalParent
_originalSiblingIndex => originalSiblingIndex
_source => source
_parentCanvas => parentCanvas

3 Likes

This is great! I’ve actually encountered that problem myself (I have a text overlay with the name of the item or slot, depending on if it has an equipped item). It’s not often I grab a student tip for my own project.

I am glad to help.

Privacy & Terms