Click or drag to resize

GuiActionsList Class

A helper to accumulate GUI actions.
Inheritance Hierarchy
SystemObject
  KSPDev.GUIUtilsGuiActionsList

Namespace:  KSPDev.GUIUtils
Assembly:  KSPDev_Utils.2.5 (in KSPDev_Utils.2.5.dll) Version: 2.5 for KSP v1
Syntax
C#
public class GuiActionsList
Request Example View Source

The GuiActionsList type exposes the following members.

Constructors
  NameDescription
Public methodGuiActionsList
Initializes a new instance of the GuiActionsList class
Top
Methods
  NameDescription
Public methodAdd
Adds an action to the pending list.
Public methodExecutePendingGuiActions
Executes actions when it's safe to do the changes.
Top
Remarks
Unity may issue multiple GUI passes during a frame, and it requires the number of UI elements not to change between the passes. Unity expects the number of UI controls in every pass to be exactly the same as in the very first one: EventType.Layout. When the UI interactions affect the representation, all the changes must be postponed till the frame rendering is ended. This helper can be used to store the actions that will be executed at the beginning of the next frame.
Examples
public class MyUI : MonoBehaviour {
  private readonly GuiActionsList guiActions = new GuiActionsList();
  private bool showLabel = false;

  void OnGUI() {
    if (guiActions.ExecutePendingGuiActions()) {
      // ...do other stuff that affects UI... 
    }

    if (GUILayout.Button(new GUIContent("Test Button"))) {
      // If "showLabel" is changed right here then Unity GUI will complain saying the number
      // of UI controls has changed. So, postpone the change until current frame is ended.
      guiActions.Add(() => {
        showLabel = !showLabel;  // This will be done at the beginning of the next frame.
      });
    }

    if (showLabel) {
      GUILayout.Label("Test label");
    }
  }
}

If you were using simple approach and updated showLabel right away Unity would likely thrown an error like this:

[EXCEPTION] ArgumentException: Getting control 1's position in a group with only 1 controls when doing Repaint

See Also