Is there a more elegant way to code saving and restoring of values?

I have eg this which conditionally disables a button:

   bool prevGuiEnabled = GUI.enabled;
   GUI.enabled = CanPerformAction();
   {
       if (GUILayout.Button("Action"))
       {
           PerformAction();
       }
   }
   GUI.enabled = prevGuiEnabled;

Which can of course stack and escalate with nested functionality. And clutter the code. Is there a more elegant way for something like this? It’s same with eg RenderTexture.active.

Basically store previous value, do something, restore original value.

You can use structs that implement IDisposable. They can first save the previous state and then apply the temporary state change in their constructor, and then restore the previous state when their Dispose method is called.

This can then be combined with the using statement to create code that is quite readable, and safer as well, since it restores the value even in the case of an exception.

Example:

public static GUIScope
{
    public static bool Enabled(bool enabled) => new GUIEnabledScope(enabled);
}

public readonly struct GUIEnabledScope : IDisposable
{
    private readonly bool wasEnabled;
  
    public GUIEnabledScope(bool enabled)
    {
        wasEnabled = GUI.enabled;
        GUI.enabled = enabled;
    }

    public void Dispose() => GUI.enabled = wasEnabled;
}
using(GUIScope.Enabled(CanPerformAction()))
{
    if(GUILayout.Button("Action"))
    {
        PerformAction();
    }
}

Unity actually already defines a couple of these structures in the EditorGUI class:

That’s awesome! Thank you very much! :slight_smile: