Hi there guys,
I was wondering if you could point me in the right direction for the serialization of scriptable objects that hold references to other scriptable objects.
I have watched a range of tutorials and attempted to research the problem but after two days have yet to come up with a functional solution. Any help would be massively appreciated.
Here are some of the resources I have managed to learn from so far:
I have a player stats scriptable which holds references to other relevant player information. This is an exerpt of the example. PlayerAbilities, Class,Inventory and PlayerEquipment are all other scriptable objects.
public class PlayerStats : ScriptableObject
{
public string playerName = "Joshua";
public Sprite playerPortrait;
public PlayerAbilities playerAbilities;
public Class playerClass;
public Inventory playerInventory;
public PlayerEquipment playerEquipment;
...
This script below allows for the serialization of a list of scriptable objects, however upon loading the game, the references set within the scriptables are lost.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
public class ScriptableObjectStateSave : MonoBehaviour
{
[Header("Meta")]
public string persisterName;
[Header("Objects to Persist")]
public List<ScriptableObject> objectsToPersist;
//On Enable this loads the state of the scriptable object list.
private void OnEnable()
{
for (int i = 0; i < objectsToPersist.Count; i++)
{
if (File.Exists(Application.persistentDataPath + string.Format("/{0}_{1}.save", persisterName, i))){
BinaryFormatter binary = new BinaryFormatter();
FileStream file = File.Open(Application.persistentDataPath + string.Format("/{0}_{1}.save", persisterName, i), FileMode.Open);
JsonUtility.FromJsonOverwrite((string)binary.Deserialize(file), objectsToPersist[i]);
file.Close();
} else
{
}
}
}
//On Disable this saves the state of the scriptable object list.
private void OnDisable()
{
for (int i = 0; i < objectsToPersist.Count; i++)
{
BinaryFormatter binary = new BinaryFormatter();
FileStream file = File.Create(Application.persistentDataPath + string.Format("/{0}_{1}.save", persisterName, i));
var json = JsonUtility.ToJson(objectsToPersist[i]);
binary.Serialize(file, json);
file.Close();
}
}
}
Could anybody give me some advice on the best practices / setup of the serializer so that these references can be maintained?
Some of the Ideas Iâve had include combining those scriptable objects into one all encompasing player scriptable object.
Another being using a Player script to handle all interactions between the scriptable objects and not have scriptable objects contained inside each other.
What would be the best course of action for this?
All the best,
Josh