Why are GUI functions called from inside of OnGUI() ?

From the script reference, the Monobehaviour.OnGUI() can be called several times per frame, depending on the events calling it.

From the Manual on the GUI Basics, it says that OnGUI is a special function that gets called every frame much like the OnUpdate function.

So then why is it all example scripts of creating `GUI` I see boxes etc being created within the `OnGUI` function, like this?

public class Example : MonoBehaviour {
    void OnGUI() {
        GUI.Box(new Rect(0, 0, Screen.width, Screen.height), "This is a title");

Wouldn’t this mean that this box get’s created over and over again every frame?

For real, everything in the game is redrawn every frame. That’s what the camera’s clearFlags do – wipe it for a total redraw. So running GUI.Box each frame is the “normal” way of drawing and has no special memory needs.

“Permanent” things, like GUITextures, are really being faked by Unity. The system is running through every gameObject, every frame and running the equivalent of GUI.DrawTexture on each one. It’s great that they feel like real objects, that are just there. And it’s great the Unity does that, with frustrum culling and the rest. But Unity didn’t change the way graphics work.

Some older systems (MS windows) would draw the scene and then save it (like a jpeg.) So once you drew an object, it was sticky. They used tricks to save/restore parts of the screen if you dragged something over it. It you later destroyed a box, only then would they recompute that part of the screen. But those only worked fast enough when you had rare, 1-time, movement. And graphics cards are set up for the “always redraw all” method.

Yes, it does mean that the box gets created over and over again every frame. That’s the idea of using immediate mode, same with other functions like Graphics.DrawMesh and so on.