Behaviour of custom inspector on Undo


I stumbled upon a problem regarding the implementation of custom inspectors (also property drawers) in combination with Undo.

The Problem

If an Undo operation is performed, the inspector is destroyed, the same way as if the inspector loses focus. The consequence is that all local fields are reset to their respective default value. E.g. a private bool foldout is set to false resulting in a folded UI.

This is of course perfectly normal if the inspector loses focus. However, as far as I know this shouldn’t be
normal for an Undo operation. At least I did not found a clear statement about the consequences of using Undo with respect to custom inspectors.
Most examples regarding custom inspectors and property drawers are using private fields to handle their foldouts and other things.

Even more mystifying is the following Example.
I experienced different behaviour in nearly identical custom inspectors. While the editor of inspector A is destroyed on Undo, the editor of inspector B is not. Both have the following structure:

public class ExampleEditor : Editor
    // Field
    private int selectedCategory;

    // Method
    public override void OnInspectorGUI()

         selectedCategory = GUILayout.Toolbar(
              new string[] { "Option1", "Option2", "Option3" });

        switch (selectedCategory)
            case 0:

            case 1:

            case 2:


The Question

What is the correct behaviour I should expect from Unitys Editor?
Is it possible to have control on weather the inspector destroys itself on Undo or not?

The Solution

Of course there is a very simple way to solve the problem. However, I think it is
important to understand the problem and to have it written down so others can
find these informations. Especially ambiguous behaviour is always a great concern.

Regarding the foldout example, it is possible to use the .isExpanded flag of a SerializedProperty.
In my case, where I need to store an integer field, it is also possible to store the field
in the serializedObject instead of the inspector.

If an Undo operation is performed, the inspector is destroyed

This should not be true. Does your inspector also currently display a material editor when this happens? If so, I actually fixed this during the 5.5 cycle. If not, I’d appreciate a bug report.

Edit: For people reading this in future, this bug was in fact fixed for 5.6, not 5.5.