EditorGUI.BeginChangeCheck() Question

Hiya,

So, I’ve got a question that can probably be answered quickly for those who know it. In editor scripts, there is the function EditorGUI.BeginChangeCheck() that “records” the following GUI elements / variables and checks to see if they have been changed when EditorGUI.EndChangeCheck() is called. Is it inefficient to stuff a bunch of variables between the two functions instead of doing this for every variable?


Example:

EditorGUI.BeginChangeCheck();
float areaOfEffect1 = Handles.RadiusHandle(...);
float areaOfEffect2 = Handles.RadiusHandle(...);
float areaOfEffect3 = Handles.RadiusHandle(...);
//...
if (EditorGUI.EndChangeCheck()) {
      Debug.Log("Change detected in variables");
}

Well, all BeginChangeCheck does is this:

public static void BeginChangeCheck()
{
	EditorGUI.s_ChangedStack.Push(GUI.changed);
	GUI.changed = false;
}

and all EndChangeCheck does is this:

public static bool EndChangeCheck()
{
	bool changed = GUI.changed;
	GUI.changed |= EditorGUI.s_ChangedStack.Pop();
	return changed;
}

So all it does is to save the current state of the “GUI.changed” variable onto an internal stack when BeginChangeCheck is called.It also ensures that the changed variable is set to false so when any change happens from now on it will be detected in EndChangeCheck.

In EndChangeCheck it simple returns the state of GUI.changed at this point and “merges” the current state with the stored state.

The overhead of those actions is minimal. The “s_ChangedStack” is a static variable with a field initializer so the instance is automatically created after a recompile and will stay around. That means no garbage is generated (except when it need to grow it’s internal capacity but this happens only at the beginning).

If you never really have a “changed” state you want to propergate to the end of your GUI code you can instead directly set GUI.changed to false before the GUI control and check it after the gui control(s) to see if any control has signalled a change. Controls should only ever set changed to true if they changed something but never to false. So setting it to false is up to you. Unity sets changed to false at the beginning of OnGUI or OnInspectorGUI. However how you treat that “changed” information is up to you. Those two helper methods are meant to keep the overall changed state throughout the entire GUI code but allows to just text a specific section for changes.

To answer your bold question: It’s of course more efficient to use less Begin / End pairs if it’s not needed. It all depends on what you actually want to do when a change happens and how important it is to distinguish what exactly has changed. The code in your question is generic without any meaningful purpose.