How to make sure the button stay on top when being dragged?

I create a game that need user to drag and drop in a box. I used Grid Layout to arrange the Buttons in a box. But when dragged, the Button is below all other elements. I already tried change to SetAsLastSibling() and SetParent() but it does not work. :frowning:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;

public class UIDrag : MonoBehaviour, IDragHandler, IEndDragHandler, IPointerDownHandler
{
    Vector3 startPosition;
    Vector3 diffPosition;
    GameObject canvas_;
    public Vector2 originalPos;
    private bool ObjOnTop;
    public static Transform saveObj;
    

    public void OnDrag(PointerEventData eventData)
    {
        transform.position = Input.mousePosition - diffPosition;
        //Debug.Log(Input.mousePosition);
    }

    public void OnEndDrag(PointerEventData eventData)
    {
        if (ObjOnTop)
        {
            transform.SetParent(saveObj);

        }
        else
        {
            transform.position = originalPos;
        }

    }

    public void OnPointerDown(PointerEventData eventData)
    {
        startPosition = transform.position;
        diffPosition = Input.mousePosition - startPosition;
        EventSystem.current.SetSelectedGameObject(gameObject);
        EventSystem.current.currentSelectedGameObject.transform.SetParent(canvas_.transform);
       EventSystem.current.currentSelectedGameObject.transform.SetAsFirstSibling();
        Debug.Log("start drag " + gameObject.name);
    }

    private void OnTriggerStay2D(Collider2D input)
    {
        if (input.gameObject.CompareTag("Drop"))
        {
            ObjOnTop = true;
            saveObj = input.gameObject.transform;
            
        }
    }

    private void OnTriggerExit2D(Collider2D input)
    {
        if (input.gameObject.CompareTag("Drop"))
        {
            ObjOnTop = false;   
        }
    }

    void Start()
    {
        canvas_ = GameObject.Find("Canvas");
       originalPos = transform.position;   
    }

    void Update()
    {

    }

}

You are using SetAsFirstSibling() instead of SetAsLastSibling()

I did tried to use SetAsLastSibling() but it will mess the Grid Layour function.

Can you provide a screen shot of what’s happening in game scene and where the gameobject is in the hierarchy when dragging.


This is the scene view when i dragged the button into a box. The button below the yellow box is called “Function”. Supposedly, when i dragged the button into yellow box, it should be on top of the yellow box when it is OnDrag().

Screenshot 2023-11-05 182430
This is the layer in hierarchy. The button is being stored under rectangle box inside canvas.

You should ask ChatGPT or BingGPT