How ONGUI and GUILayout.Button works internally

I have a curiosity about how the OnGUI method works internally. I see that buttons are created but no references are made to them and no callback function is passed either. For what I understood at the first frame the window is drawn and in subsequent ones GUILayout.Button returns the state of the buttons that had already been drawn. The thing I don’t understand is how internally the GUILayout.Button method manages to have a reference to a button that it had already drawn if in fact no reference was kept in a variable. I wonder therefore how does the GUILayout.Button method know that it must not create a button (when it is not executed for the first time) but must return the button state and how it knows what button it is, if it has no reference to it?

Link of API Scripting example: Unity - Scripting API: GUILayout.Button

My guess is that it is creating some sort of reference internally that it is remembering between calls to OnGUI (possibly related to the call order of the buttons, e.g. it assumes that the 42nd call to GUILayout.Button is going to be the same button)

Ok, but some GUILayout.Button could be inside an if statement depending on some variable so the call to next GUILayout.Button could reference to wrong button. What do you think about?

The immediate mode stuff generates ID’s for each control, and those ID’s are sequential (kinda). That means that if you change the number of elements, things will break. For example, if you have a button to toggle a bool, and you then draw elements after that if or if not the bool is true, you’ll get errors.

1 Like

If I have understood, we must not put GUILayout.Button (or other stuff) inside an if statement, otherwise we have a crash? If it is so the GUI is not very well designed.

You can put GUI controls in if statements (that’s entirely how GUILayout.Button is supposed to work), you just need to be careful and be aware of how OnGUI works to avoid problems.

If you mess up, it’s not going to crash, it will just log an error in the console.

Ok thank you