How to remember the state (value) of Foldouts when closing and reopening a EditorWindow?

I have a custom Inspector using EditorWindow, something liket this:

public class IlluminationInspector : EditorWindow
{
    [MenuItem("Illumination/Illumination Inspector _I", false, 0)]
    public static void ShowWindow()
    {
        var window = GetWindow<IlluminationInspector>();
        window.titleContent = new GUIContent("Illumination Inspector");
        window.minSize = new Vector2(250, 50);
    }
}

I have a lot of foldouts in this window to keep things organised and provide a userfriendly overview. But when I close the window and open it again it does not remember the state of the foldouts, i.e. whether they were opened or closed the last time I used the window. Is there some way of storing the states of foldouts? I tried declaring variables for it but those are reset when the windows is opened. It would also be good if the states were remembered even after Unity itself has been closed and restarted. So these values need to be stored on disk somehow?

What is the best practice or intended workflow for this scenario?

1 Like

Use the string property “VisualElement.viewDataKey”!

Read the online documentation:

Learned from this post .

What I’m currently doing:

private string GetFoldoutDataKey(SerializedProperty property)
{
    return $"{property.serializedObject.targetObject.GetInstanceID()}.{property.name}";
}

I don’t know if this is the recommended way, but it works!