- Home /
Question by
AndreiKubyshkin · May 24 at 09:52 AM ·
c#serializationscriptableobjectserializefield
Serialized Field on Scriptable object is lost on editor reload
Hey Folks!
I have a class derived from scriptable object that has the _id field used for the save system.
For some reason the _id is being reset each time I reload the Unity editor.
Am I doing something wrong? What could be the case?
Unity version I'm using is 2019.4.31f1
Class example:
public class PresetWithID : ScriptableObject
{
[HideInInspector][SerializeField] string _id = System.Guid.NewGuid().ToString();
public string ID => _id;
}
Comment
Best Answer
Answer by AndreiKubyshkin · May 24 at 11:41 AM
So it seems that _id won't get serialized until it's being manually changed from inspector. The solution I came up to is to set the _id in the Awake() and execute the EditorUtility.SetDirty() after that.
public class PresetWithID : ScriptableObject
{
[SerializeField, InspectorReadOnly] string _id = string.Empty;
public string ID => _id;
#if UNITY_EDITOR
void Awake()
{
if(string.IsNullOrEmpty(_id))
{
_id = System.Guid.NewGuid().ToString();
UnityEditor.EditorUtility.SetDirty(this);
}
}
#endif
}