- Home /
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?
Answer by vexe · Apr 21, 2014 at 08:44 AM
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
...
Thank you for your insight. Your solution works but I'm looking for a more... ideal one :) I think the behaviour shouldn't even have to know that there is an editor for it, much less contain information that is used only by the editor. (If I go to a doctor I shouldn't have to tell them how to inspect me :)
I guess it's just a matter of how much you want to abide by the decoupling principles, so it's kind of an academic question. Still I'd like to know if there is any way to have that data closer to the editor, either in itself or some intermediate place.
Using preprocessor is pretty neat, though.
Your answer
Follow this Question
Related Questions
How should I serialize data that is also editable in the Inspector? 2 Answers
Custom Editor for Monobehavior with custom property not retaining Gameobject references 0 Answers
Editable non-monobehaviour objects 1 Answer
Custom editor tags not saving 1 Answer
Custom Inspector Horiztonal Vector2 and Button Spacing 0 Answers