Search code examples
user-interfaceunity-game-enginedrag-and-dropforegroundtopmost

Bring a UI Element to foreground


I would like to implement simple drag and drop with:

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

The problem is that when i begin the drag, I want to bring the UI Element to the foreground. by doing something like this:

public void OnBeginDrag (PointerEventData eventData)
{
    transform.SetParent (transform.parent);    // giving the parent transform or a transform of an element on top
}

This obviously isn't a general solution. So I have a question. Is there an elegant way on how to make a UI element topmost?


Solution

  • I've actually found a pretty simple solution. After setting the UI Element transform to:

    transform.SetParent(transform.root);
    

    The UI Element is placed as the first child of the Canvas, thus effectivly placing itself to the foreground.