- Home /
Serialize a variable in a custom inspector?
It seems like mocking stuff with [SerializeField]
in an Editor
class won't serialize the thing after an assembly reload. I have a simple boolean to represent a fold status for my editor - I want to serialize it. i.e. let's say I unfolded in editor mode, went to play mode and see that it's still unfolded.
The way I used to do it is have the boolean stored in the target
MonoBehaviour
- (the type whom I'm making the editor for) - but that's just not clean, why does that MB have to store something, only its editor needs? it doesn't make sense.
Here's what my editor looks like:
If knowing any code would help you, let me know.
Thanks.
Answer by gfoot · Feb 01, 2014 at 11:36 AM
You need to store the data somewhere persistent. It works in the MonoBehaviour because Unity serializes it and recreates it after the code reload. Other than that, you could use EditorPrefs to store your editor-only data, but if you want to store this attribute per instance (so the expanded/collapsed state is stored separately for different edited objects) then it will get tricky.
thanks for your answer! - I've never used EditorPrefs before so this might be a good chance. But why is it tricky to save individual folds? if it's just a bool then I think it should as easy as saving the main fold. I'll give it a shot.
EditorPrefs stores data as key-value pairs. You need a way to create keys that are somehow linked to the $$anonymous$$onoBehaviour being edited. I'm not sure the best way to do that - maybe you can use GetInstanceID().
The other thing you may or may not want is these prefs persist forever - they're stored in the registry - so when you close the editor then open it again later on, it will remember the folds. I don't know whether that suits your needs or not.
I guess another place you could store this data is within a ScriptableObject instance in the Assets folder. Your ScriptableObject could contain a list of $$anonymous$$onoBehaviour instance IDs along with any editor data you want to store linked to that $$anonymous$$onoBehaviour. You would need to make sure the ScriptableObject is correctly serialised of course.
Thanks I kind of took Bunny's approach of using conditional compilation http://answers.unity3d.com/questions/216395/editorguilayoutfoldout-no-way-to-remember-state.html
I don't really care if the values are saved between editor sessions. I considered just saving the values manually to a file, and loading them back... however, I prefer conditional compilation ins$$anonymous$$d.
Your answer
![](https://koobas.hobune.stream/wayback/20220613132240im_/https://answers.unity.com/themes/thub/images/avi.jpg)