How do Text Fields work? (Backend)

Recently I have been making my own GUI module in python, and I have been modelling it after the one used in Unity. I just love the way everything is put together in Unity!
So I have gotten to the stage where I have to pass 2 values into my text field function, in order to save both the text and weather or not the field is active, but Unity seems to do this automatically???

How does it work?
How does Unity keep track of which text field is active, when I can add any text field anywhere at any time…

If backend questions arn’t supposed to be here, please just tell me and I’ll delete the question :slight_smile:

Thank you, Benproductions1

Ps: I’m not looking for code, just an explanation of how the Unity GUI text field works in the backend :slight_smile:

EDIT:
Let me clear this up a little bit.

I am asking, how unity manages to do text fields by only supplying the text and not an active value
AKA: Why is it text = GUILayout.TextField(text); and not text = GUILayout.TextField(text, ref active);

Thankn you

Aha! Now I gotcha.

The OnGUI function runs ‘in steps’, at least twice per Update (Layout and Repaint steps). The GUI functions do different things during different steps, to the point where it’s possible that I’ve needed to manually ‘wait until step X’ in some particularly tricky GUI nonsense.

You can check if you’re in Layout mode (the only check I’ve needed) inside OnGUI with:

(Event.current.type == EventType.Layout) => in Layout step

Unity calls OnGUI frequently with different event types. The logically-first step is Layout, in which the GUI* functions create GUI elements (which are a complex class of their own) and assign them IDs. Next is Repaint, in which the elements are drawn.

I don’t know exactly how Unity handles the active control, but I’m reasonably certain that it simply keeps track of its internal ID of the active control, and changes that based on user input. The elements are recreated every GUI call (unless Unity caches them with some magiclogic), but if they’re the same elements they have the same ID and so you keep the same active control.

You can sort-of see the results of this if you have a GUI setup with several text fields, and you remove one or more while entering text - the entered text magically transfers to other fields as Unity gets confused about them (I have yet to experience any functional defect from this behaviour; as far as I can tell it’s all cosmetic).