- Home /
UnityEngine.Object field pointing to Project file gets serialized by JSON as instance ID. After deserialization field points to different Object. Why?
I'm writing todo list in EditorWindow. All it's data is being serialized as separate text JSON files. One of the fields in every entry is of type UnityEngine.Object and they are pointing to Project files for some context (serialized by JSON as instanceID). But problem is: after editor restart and deserialization this field now points to very different Object.
I observed that one particular asset has id of "19658" but reference to it gets serialized as different number, "16670" for example. I suspect instanceID is not good value to use but I'm not sure what is the best way to go about it. Any ideas?
Serialize Object field as asset path instead? (not ideal as easily breakable)
Some another type of GUID?
Answer by troien · Sep 01, 2016 at 09:51 AM
I'm doing this out of my head and I'm not 100% sure. But I believe InstanceID as you describe does not survive serialization/deserialization (I thought that it for this reason didn't even survive going in/out of playmode but I'm not sure on that one).
Anyway, I believe you actually provided the answer kinda with your question :p
Use the guid, which you can find from the assetpath
AssetDatabase.GetAssetPath()
AssetDatabase.AssetPathToGUID()
AssetDatabase.GUIDToAssetPath()
AssetDatabase.LoadAssetAtPath()
Thank you! Worked like a charm.
Solution example for future reference:
[System.Serializable]
class SomeClassWithObjectField : ISerializationCallbackReceiver {
#region fields
[System.NonSerialized] public Object subject;
[SerializeField] string _subject;
#endregion
#region ISerializationCallbackReceiver implementation
public void OnBeforeSerialize () {
if( this.subject!=null ) {
this._subject = AssetDatabase.AssetPathToGUID(
AssetDatabase.GetAssetPath( this.subject )
);
}
else {
this._subject = null;
}
}
public void OnAfterDeserialize () {
if( this._subject!=null ) {
this.subject = AssetDatabase.Load$$anonymous$$ainAssetAtPath(
AssetDatabase.GUIDToAssetPath( this._subject )
);
}
}
#endregion
}
Your answer
Follow this Question
Related Questions
When does the "InstanceID" get assigned, and does it seralize with the Object? 2 Answers
EditorWindow - Child class gets cast back to parent class at compilation. 2 Answers
How do I go about deserializing a json array? 3 Answers
What are the pros and cons of ScriptableObjects vs. JSON for data files? 2 Answers
How do serialized Texture2D fields store and manage Texture2D data pulled from a dll ? 1 Answer