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?
2 Answers
2
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.
My guess: While it does mean the GUI.Box() function gets called multiple times per frame, it only does any significant work on a EventType.Repaint type of call. Likewise a Button() call likely does it display during a EventType.Repaint, but does its button processing (i.e. texting for a click) on an EventType.MouseUp.
– robertbuHand coding a game in directX, I was taught that each frame it calls the backbuffer to get a basic knowledge of what's happening. So, if you don't update the buffer, backbuffer would auto clear the gui. If you wanted I bet you could make your own doGui() function and you only update it on an event. I'm still pretty new to unity, but its the same concept as the 3d functions. If you don't call a variable update on every update() the result will look the way it did say for example last time you clicked.
– KuPAfoo