Skip to main content

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

Comments

Popular posts from this blog

How to delete Hot Apps folder on Oppo Realme

Bloat wares are the single worst enemy of anyone who just wants a simple experience with the mobile phones. Oppo goes to a next level in spamming stuff we don't need by their Hot Apps shortcut on Homescreen. And it is not always available in a new phone but comes after few hours sometimes days of usage. To disable this icon/folder/shortcut follow the steps below. 1. Open Settings. Swipe down the notification bar and open settings. 2. Open OPPO AppStore settings. Scroll all the way down and click OPPO AppStore. 3. Disable Homescreen folder for hot apps. That's it. You can also disable notification alert from App Store and Browser for even better Android experience as these apps spam a lot.

How to fix clothes flickering in Unreal Engine 5.

 This issue can be noticed some of the character clothes when using Paragon Characters in UE5. To fix the flickering issue, Use Self Collisions checkbox in collisions properties under the Static Mesh option of your character. Open the character model go to   Asset Details > Clothing Properties - Cloth Config - ChaosClothConfig - Collision Properties - Use Self Collisions > False

How to make download file button in react js

To create a download file button in React.js, follow these steps: Import the necessary dependencies: javascript Copy code import React from 'react' ; import { saveAs } from 'file-saver' ; Create a function that handles the download action: javascript Copy code const handleDownload = ( ) => { // Create a new Blob object with the desired content const fileContent = 'This is the content of the file you want to download.' ; const blob = new Blob ([fileContent], { type : 'text/plain;charset=utf-8' }); // Use the saveAs function from the file-saver library to initiate the download saveAs (blob, 'download.txt' ); }; Create a button component and attach the handleDownload function to the button's onClick event: javascript Copy code const DownloadButton = ( ) => { return ( < button onClick = {handleDownload} > Download File </ button > ); }; Use the DownloadButton component wherever ...