How to draw element beneath/ontop with onGUI without GUIdepth?

Okay, so apparently GUI.depth is only applicable if you have multiple scripts with onGUI. Fair enough. My issue:

private void onGUI {
if (condition) {
	int e = 0;
	float posY = 980f;
	toggle = GUI.Toggle(new Rect(320f, posY - (float)(e++ * 20), 150f, 20f), toggle, "text");
	toggle2 = GUI.Toggle(new Rect(320f, posY - (float)(e++ * 20), 150f, 20f), toggle2, "text2");
	//lots of toggles
	//drawing box label because we have final [e]
	GUI.Label(new Rect(318f, posY - (float)(e++ * 20) + 2f, 154f, (float)(e++ * 20)), "", "box");
	//restoring other GUI stuff etc

I wanna draw a nice box beneath toggles. I could move it up so it will be drawn before toggles but then I would not know the final [e] for the height value…

Any ideas?

Well, either you simply use GUILayout instead that would simplify everything as you don’t have to manually track the position of the elements. This is pretty much the only way as the immediate mode is drawn “immediately”. So elements drawn later always appear on top of other elements. So it’s impossible to draw something beneath an already drawn element.

Another way is to simply use the Layout event to store the final height at the end of the OnGUI method during the layout event so you can use that value during the repaint event.

This should result in the same as your “manual logic”:

void OnGUI()
    GUILayout.BeginArea(new Rect(320,0,150,1000));
    toggle = GUILayout.Toggle(toggle, "toggle1", GUILayout.Height(20));
    toggle2 = GUILayout.Toggle(toggle2, "toggle2", GUILayout.Height(20));

First we define a new layout area that goes from the top of the screen down to “1000” and covers exactly the area you want on the x axis.

The first element inside the area is a flexible space which will “eat up” all left over space and will “push” everything else that comes below downward.

Now we simply create a new vertical layout group with the box style. We actually are already in a vertical group (which is the default direction) but this doesn’t include the flexible space so the box does only cover the actual elements.

Now just define your elements as many as you want. I forced all elements to a height of “20”. However you may want to remove that. If an element would need to be larger that would be automatically arranged. For example a TextArea with multiple lines would simply grow in height if needed. See the GUILayoutOption page for more constrainst you can apply to layout elements.

Note that the order of the element will be the actual order in which you specified the elements. You did arrange them in reverse order.

Also note that you can (if needed) create a Horizontal group inside the vertical if you need to arrange two or more elements in a row.