How to make sure Background GUI gets drawn first?

Hi,

I'm trying to build a GUI with GUI.Button, GUI.Box, etc. with C# scripts.

The GUI is scattered among several objects in the scene (...was that a wise move?) and now I want to draw a background for my GUI elements. The background is build from 128x128 tiles.

The problem is that my "background" actually gets drawn on top of my buttons. How do I best avoid that? It doesn't seem to matter if I draw the background tiles with GUI.Box or GUI.Texture, the result remains the same.

On your OnGUI method, set GUI.depth to control the order in which GUI elements are drawn. Set it to a high number for your background and a low number for the foreground.

I strongly recommend grouping your GUI to a single script, for this reason among others. If you group your OnGUI to a single function in a single script, you can decide exactly what order the GUI is drawn.

If you do this, simply place your background code before your button/objects code in the OnGUI function, and the objects should be drawn on top.

If you choose to keep your GUI across multiple scripts, it might be good to ensure your background object is higher in the scene hierarchy. I'm not familiar with unity script execution order, but if it is based on hierarchy that should help.

Make a GUI Manager object which manages a set of delegate GUI function with a priority.

Make your Monobehaviour Objects add their gui function to the manager with their designated priority. Remove the code from your OnGUI to this function.

Then have the GUI manager object handle the GUI functions in the right priority order through its OnGUI.

In the end you will have only one OnGUI.