- Home /
How to serialize a reference to a ScriptableObject asset file using the JsonSerializer
Hi, I'm trying to serialize a ScriptableObject that references several arrays of other ScriptableObject classes using the builtin JSON Serialization. This serialization needs to be done at runtime and all the referenced ScriptableObjects exist as actual assets in my project folder.
here is the code from the class i'm trying to serialize so far:
public class Inventory : ScriptableObject {
[Header("Upgrades")]
public Collector[] collectors;
public Fin[] fins;
public Turbine[] turbines;
}
public class Upgrade : ScriptableObject {
}
[CreateAssetMenu]
public class Collector : Upgrade {
[Header("Collector Modifiers")]
[Range(0.5f, 2f)]
public float maxCargo = 1;
[Range(0.5f, 2f)]
public float collectRadius = 1;
[Range(0.5f, 2f)]
public float recyclingBonus = 1;
}
and this is the output that i get when I serialize the Inventory class:
var json = JsonUtility.ToJson(inventory);
{
"collectors": [
{
"instanceID": 12822
},
{
"instanceID": 11936
},
{
"instanceID": 10726
}
],
"fins": [
{
"instanceID": 10636
},
{
"instanceID": 10802
}
],
"turbines": [
{
"instanceID": 10364
},
{
"instanceID": 11142
}
]
}
Which is sort of what I want. I want the json to store only the references of the ScriptableObjects. And this is kind of what I'm getting here but my problem is that these InstanceIDs will have changed after unity is restarted, and, in consequence of that, I will lose all my references on the next play session.
I understand that ScriptableObjects dont necessarily need to be associated with an actual asset file but in this case I can assure they will. What I want is an easy way to store and retrieve a reliable reference to these assets at runtime.
Have anyone came across a similar situation? Any suggestion on how to approach this problem?
Answer by TonyLi · Dec 13, 2016 at 06:36 PM
According to the release notes, Unity 5.5.0 now serializes references by persistent fileID, not by ephemeral instanceID as in previous versions.
Answer by $$anonymous$$ · Jun 26, 2017 at 03:42 PM
That only works in the editor. Is there a way to do this at run time too?
I haven't found a release version of Unity that does this correctly. (Either that or I'm doing something wrong.) You'll probably have to maintain your own unique referencing system.
Your answer
Follow this Question
Related Questions
Serialize a list of scriptable objects to Json 0 Answers
ScriptableObject error with Inheritance 2 Answers
ScriptableObjects in a List all become nulls on Play 0 Answers
Distribute terrain in zones 3 Answers
Cannot serialize System.Type field 3 Answers