Saving reference to a ScriptableObject with JsonUtility
I have a data structure like the following
[Serializable]
public class InventoryWrapper
{
public CardInventory[] Data = new CardInventory[0];
}
[Serializable]
public class CardInventory
{
public CardDefinition Definition;
public int Quantity;
}
CardDefinition in the example above is a ScriptableObject class. I'm using the JsonUtility.ToJson and JsonUtility.FromJson functions to save this data structure to disk and loading later. It appeared to work fine and generates output as follows:
{
"Data":[
{
"Definition":{
"instanceID":377496
},
"Quantity":2
},
{
"Definition":{
"instanceID":377502
},
"Quantity":2
},
{
"Definition":{
"instanceID":-2897598
},
"Quantity":2
}
]
}
This morning all my references broke and when the data is serialised FROM JSON I get null objects instead of references to my ScriptableObjects. Am I going about this in the wrong way? Can anyone help
Is it just me or your last instanceID seems weird (Is negative -2897598).
Did you managed to fix this? I just encountered same problem
No. I ended up referencing them by name and hoping the filenames never change.
instanceID is unique for each session of Unity. It will be changed when you restart Unity.
Why would Unitys serialisation save an ID that changes in every session? That makes no sense.
Answer by Deadcow_ · Nov 21, 2017 at 04:01 PM
Ok, that was easy. To write GUID instead of InstanceId (i.e. preserve object references) we need to use EditorJsonUtility instead of JsonUtility
EditorJsonUtility exists only in the UnityEditor namespace. There's no use for it in a game.