Scriptable objects, can I use them to save/load while the game goes?

I’ve been trying to understand how to use scriptable objects correctly and efficiently, and when i thought I understand something I’ve overcame one problem that bothers me. So when I have e.g. class that contains players health, exprience etc. I want to make some funcion that saves it. I came easy for me to create a scriptable object that stores this information, and then I’ve created a saving and loading methods, where I use AssetDatabaseto create an asset and to load it. And it worked well, but… AssetDatabase is part of UnityEditor namespace, which cannot be included in final build (that’s what I’ve managed to establish so far). So my question is; is there any possibility to use scriptable objects to save and load such data while the game goes, or they are just not for that and the best way to store this data is storing it as a binary file using c# serializaion?

Here is how i do it:

using UnityEngine;
using System.Collections;

[System.Serializable]
public class Simple_class {
    public int simple_int;
    public string simple_string;
}
using UnityEngine;
using System.Collections.Generic;

public class Simple_scriptable_obj : ScriptableObject {
    public List <Simple_class> simple_list_to_store_data = new List <Simple_class>();

}
using UnityEngine;
using UnityEditor;
using System.Collections.Generic;

public class Game_manager : MonoBehaviour {
    public List <Simple_class> simple_list = new List <Simple_class>();

    void Update () {
        if (Input.GetKeyDown (KeyCode.F5))
            Save ();
        if (Input.GetKeyDown (KeyCode.F9))
            Load ();
    }
    public void Save () {
        Simple_scriptable_obj savedData = ScriptableObject.CreateInstance <Simple_scriptable_obj> ();
        savedData.simple_list_to_store_data = simple_list;
        AssetDatabase.CreateAsset (savedData, "Assets/savedData.asset");
        AssetDatabase.SaveAssets ();
        AssetDatabase.Refresh ();
    }
    public void Load () {
        Simple_scriptable_obj loadedData = AssetDatabase.LoadAssetAtPath <Simple_scriptable_obj> ("Assets/savedData.asset");
        simple_list = loadedData.simple_list_to_store_data;
    }
}

And as i said it wors ok in editor; I can save all changes by pressing F5 and load them with F9 but i cannot build the game, because of using UnityEditor…

ScriptableObjects are only for data that are created in the Editor.
Here is a useful link with some explanation: Can you use a ScriptableObject to save game state? - Questions & Answers - Unity Discussions
You can create the data in the Editor and save it in ScriptableObjects but if you need to write data back at runtime you need another solution. (Search for ‘Serialization’)

1 Like

Thanks much, that explains everything.

You can serialise Scriptable Objects: