Drag N Drop intantiated objects on top of each other in Unity

I have 5 instantiated objects on panel 1. I want to take items 1 by 1 from panel1 and drop them in panel2. Every item i drop in panel2 should lay on top of the previous item I dropped.
The problem is it seems to be following the order in which the items were instantiated in panel1 and I am not able to always stack the item onto the previous item. Some items go behind and some item stay on top…
e.g

  • I take the 3rd item from panel 1 and drop in panel 2
  • Then i take 4th item from panel 1, and drop in panel 2. It appears on top of the previously dropped object as I want it to.
  • Then If I take the 1st or 2nd instantiated object from panel 1 to drop into panel2, it goes behind the currently existing objects in panel2.

I tried using the SetAsLastSibling method on the OnEndDrag method as well as on the OnBeginDrag method. But the issue with this is:

  • I take the 3rd item from panel 1 and drop in panel 2
  • Then I take 4th item from panel 1. But as soon as I click on it the previously dropped item in panel2 comes back to panel 1 and it gets set as the last sibling in panel 1.

This is the code in the drag script:

public class Drag : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler
{
    public string playArea = "PlayArea";
    public string playerHand = "PlayerHand";
    public static GameObject itemBeingDragged;
    static public Card cardTmp;
    public Vector3 startPosition;

    public void OnBeginDrag(PointerEventData eventData)
    {
        itemBeingDragged = eventData.pointerDrag;
        startPosition = eventData.position;
        GetComponent<CanvasGroup>().blocksRaycasts = false;
    }

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

    public void OnEndDrag(PointerEventData eventData)
    {
        if (eventData.pointerEnter != null && (eventData.pointerEnter.transform.name == playArea || eventData.pointerEnter.transform.name == playerHand))
        {
            itemBeingDragged.transform.position = eventData.position;
        }
        else
        {
            itemBeingDragged.transform.position = startPosition;
        }
        GetComponent<CanvasGroup>().blocksRaycasts = true;
    }

}

Issue as shown below:
objectgoesbehind