OnGUI doesn't seem to be the correct place for creating LAbels

Hi,

OnGUI runs a lot and I think it is inefficient to create all of our GUI elements within it such as OnGUINode. Is there a better place we could do this, such as OnSelectionChange or some such so that it only does all the processing at the start and then only when there is an actual change. My main issue is having this foreach loop in there:

foreach (DialogueNode childNode in selectedDialogue.GetAllChildren(node))
            {
                EditorGUILayout.LabelField(childNode.text);
            }

As we are running this every GUI interaction even when there is no change, we should really only do this once at the start and again when we know there is a change.

It’s just not how IMGUI works. The inspector recreates the view every time. If it’s not created in OnGUI, it’s not going to be in the inspector. You can call methods from OnGUI to create it, so it doesn’t actually have to be in the OnGUI method, but it has to be created when OnGUI runs. Unity does at least 2 passes through OnGUI - once to measure what it’s going to draw, and once to actually draw it. But it needs to be created there.

As @bixarrio noted, in IMGUI, this is impossible, because we don’t actually have any form of reference to the labels once the LabelField is created.

Using the newer UI Elements, this is possible, as the components are retrievable, but even with this system some destruction and redrawing are often necessary.

1 Like

Can the newer UI Elements be used for Unity WIndow UI or only in game?

Can you post a link to documentation on the new Unity UI you refer to?

UI Elements are compatible with both Editor and Runtime. We currently have a introductory course in UI Elements, where Gary walks you through creating a Task Manager within the Editor, but it does not extend to runtime because at the time we made the course Runtime elements were not terribly reliable. (They’re actually great now).

Here’s a link to Unity’s documentation on the UI Toolkit.

Privacy & Terms