Save and load from scriptable objects in Unity complete workflow

 




##########################

1. Create a scriptable object class as following and create the scriptable object in Resources folder in project directory

##########################


using System.Collections;

using System.Collections.Generic;

using UnityEngine;


[CreateAssetMenu(fileName = "Data", menuName = "Data/SaveFile", order = 1)]

public class Saves : ScriptableObject

{

    public List<KeyValueData> savedDataList;


}



[System.Serializable]

public struct KeyValueData

{

    public string key;

    public string value;

}



##########################

2. Read and log saved data

For reading create a SaveSystem class as follows

##########################

using System.Collections;

using System.Collections.Generic;

using System.IO;

using System.Runtime.Serialization.Formatters.Binary;

using UnityEngine;


public static class SaveSystem

{

    public static SavedDataSerializer LoadData()

    {

        string path = Application.persistentDataPath + "/SaveFile.asset";


        Debug.Log(path);


        if (File.Exists(path))

        {

            BinaryFormatter formatter = new BinaryFormatter();

            FileStream stream = new FileStream(path, FileMode.Open);

            SavedDataSerializer deSerializedData = (SavedDataSerializer)formatter.Deserialize(stream);

            stream.Close();

            return deSerializedData;

        }

        else

        {

            return null;

        }

    }

}



[System.Serializable]

public class SavedDataSerializer

{

    public List<KeyValueData> serializedData = new List<KeyValueData>();


    public SavedDataSerializer(Saves saveableData)

    {

        serializedData = saveableData.savedDataList;

    }

}



##########################

3. Read data from any class by logging SaveSystem.LoadData();

> currently gives null as the file does not exists in local memory, we can paste the scriptable object asset at the path that is logged from line number 13(46 in this file) in above script

> Upon trying to log the data received error: SerializationException: The input stream is not a valid binary format.

> This suggests that I need to save it in binary format first then only I'll be able to read it.

> In order to directly read the Scriptable Object, I can set the reference to it in a script and read the data from it, as follows:

##########################


public class StatsManager : MonoBehaviour

{


    public Saves savedDataSO;

    // Start is called before the first frame update

    void Start()

    {

        //Debug.Log(SaveSystem.LoadData());



        foreach(KeyValueData keyValueData in savedDataSO.savedDataList)

        {

            Debug.Log("Key: " + keyValueData.key);

            Debug.Log("Value: " + keyValueData.value);


        }




    }


}




##########################

4. Now that we can load a Scriptable Object, let's save it to the location where it is supposed to be in memory

> Add following function to SaveSystem.cs

##########################


public static void SaveData(Saves saveData)

{

    BinaryFormatter formatter = new BinaryFormatter();


    string path = Application.persistentDataPath + "/SaveFile.asset";


    FileStream stream = new FileStream(path, FileMode.Create);


    SavedDataSerializer serializedLevelsData = new SavedDataSerializer(saveData);


    formatter.Serialize(stream, serializedLevelsData);


    stream.Close();



}



##########################

5. Call SaveData after loading the placeholder data from scriptable object in order to save it in binary format

> running the following function should create the file SaveFile.asset in the location(Application.persistentDataPath) that was logged earlier

##########################


public class StatsManager : MonoBehaviour

{

    public Saves savedDataSO;

    // Start is called before the first frame update

    void Start()

    {

        //Debug.Log(SaveSystem.LoadData());


        foreach(KeyValueData keyValueData in savedDataSO.savedDataList)

        {

            Debug.Log("Key: " + keyValueData.key);

            Debug.Log("Value: " + keyValueData.value);


        }



        SaveSystem.SaveData(savedDataSO);

    }


}



##########################

6. Now we should be able to read the saved data

> now if we run the code below it should log the data from the saved location

##########################


public class StatsManager : MonoBehaviour

{


    void Start()

    {


        SavedDataSerializer savedData = SaveSystem.LoadData();


        foreach(KeyValueData keyValueData in savedData.serializedData)

        {

            Debug.Log("Key: " + keyValueData.key);

            Debug.Log("Value: " + keyValueData.value);

        

        }


    }


}



##########################

7. This finishes Scriptable Object based save and load system. Now in order to utilize if properly, we need to setup following few things:

> Check if saved data exists,

if exists

> load saved data

if not

> save referenced scriptable object data to location

> Save data to location when data is updated

Previous Post
No Comment
Add Comment
comment url