My code:
public class TestWindow : EditorWindow
{
[MenuItem("Tools/OpenWindow")]
public static void OpenWindow()
{
GetWindow<TestWindow>().Show();
}
private void OnGUI()
{
if (GUI.Button(new Rect(100, 100, 100, 100), "A"))
{
Debug.Log("A");
}
if (GUI.Button(new Rect(120, 120, 100, 100), "B"))
{
Debug.Log("B");
}
}
}
You simply can’t this way. The immediate mode handles the events immediately in the order your controls are drawn. Also they are drawn in the same order. Therefore the last element (if they overlap) will always be drawn on top of the other. However the first element will always handle the events first.
Active GUI elements simply should not overlap. If you have some sort of popup menu, use a GUI.Window / GUILayout.Window. Windows are drawn based on an internal z ordering (which can be changed) and they process input events in reverse order. So the top most window will get input events first, even it is drawn last.
If the layout is known and you know the overlapping area you could manually exclude the overlapping area from the first element. But this is kinda hacky
For example in your example case it could look like this:
Event e = Event.current;
Rect overlap = new Rect(120,120,80,80);
GUI.enabled = !(e.isMouse && overlap.Contains(e.mousePosition));
if (GUI.Button(new Rect(100, 100, 100, 100), "A"))
{
Debug.Log("A");
}
GUI.enabled = true;
if (GUI.Button(new Rect(120, 120, 100, 100), "B"))
{
Debug.Log("B");
}
Here we simply disable the first button when a mouse event is processed and the mouse position is inside the overlapping area. This way the first button can’t react to mouse events.