Can I serialize data in an Editor class?

I have a custom inspector for a MonoBehaviour. The target is a singleton, and there is only one in a scene at any time. I’d like to preserve, among other things, the state of the editor foldout booleans when changing inspector target (selecting different objects) and (de)serializing the scene. The way I currently achieve it is by having the foldout booleans stored in the editor target, and while it works, the editor state doesn’t really belong there.

I haven’t succeeded in storing them in the editor object itself. It seems that it may be recreated each time you start inspecting the target, and it doesn’t live in the scene hierarchy so it’s not serialized. (I’ve tried the System.Serializable and SerializeField attributes, different HideFlags and setting the editor object dirty, to no avail.) The Editor class derives from ScriptableObject but where does it live? Can I force it to persist in the scene? Or create and use a scene object (like a MonoBehaviour) with certain HideFlags without leaking stuff? Is there some API like EditorPrefs but per-scene?

the editor state doesn’t really belong there.

Why not? - Sure, when you build, you don’t need anything editor-related in your behaviours. But at edit-time, you could say that the behaviour needs that information in order for it to be inspected properly.

But since we don’t need that state code at build, you could just use conditional compilation:

public class Target : MonoBehaviour
{
   // ...
   #if UNITY_EDITOR
   [SerializeField, HideInInspector]
   private bool fold;
   #endif
}

It’s private, no one needs to know about it - from your editor script, you could fetch the value easily if you’re using SerializedProperties via var spFold = serializedObject.FindProperty("fold"); and then use spFold.booleanValue