Martin Rončka
Martin Rončka

Reputation: 323

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?

Upvotes: 1

Views: 2574

Answers (2)

Martin Rončka
Martin Rončka

Reputation: 323

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.

Upvotes: 1

Gary Olsson
Gary Olsson

Reputation: 1217

Yes, if you're using unity GUI system, you could create some kind of layers with GUI.depth.

GUI elements drawn with lower depth values will appear on top of elements with higher values (ie, you can think of the depth as "distance" from the camera).

Here's an example :

function OnGUI() {
    GUI.depth = 1; // You set to 1 by default
    if(GUI.RepeatButton(Rect(0,0,100,100), "My Button")) {
        GUI.depth = 0; // When the button is clicked, Depth is set to 0 the button is on top 
    }
}

For my part, I usually use NGUI which is very efficient & optimized and allow you to handle drag & drop.

However, if you're not using Unity GUI (if you use gameObjects) and don't want to use a plugin, you'll need to develop your own system. The easier way to achieve the desired effect is :

  • First you need to have an orthographic camera for drag & drop element. You should adjust camera's layer accordingly.

Orthographic : Camera will render objects uniformly, with no sense of perspective.

  • Then, OnDrag you should move the object closer to the camera. This way, it'll appear to be the nearest.
  • Finally, OnDrop, you should reset object Z position to be at the same distance from your camera than any other object.

Upvotes: 2

Related Questions