Skip to content

Latest commit

 

History

History
30 lines (28 loc) · 1.39 KB

ScriptableObject.md

File metadata and controls

30 lines (28 loc) · 1.39 KB

Pitfalls

I wrote a server using UnitySocket and used ScriptableObject as the database in order to achieve lightweight. However, I found in the later stages of development that the saved data would disappear when the UnityEditor layer was exited or the packaged exe file was exited, which was not what I wanted.

Solution

In the UnityEditor layer, you can call the following code to save the corresponding resources when closing.
But an error will be reported during the packaging process
Related articles:

EditorUtility.SetDirty(obj);
AssetDatabase.SaveAssets();

The correct way to handle this is to use Unity's own JsonUtility to serialize the data in ScriptableObject for persistent storage.

string json = JsonUtility.ToJson(obj);
File.WriteAllText(Application.persistentDataPath + "/Data.json", json);

if (File.Exists(Application.persistentDataPath + "/Data.json") && !Init)
{
    string jsonStr = File.ReadAllText(Application.persistentDataPath + "/Data.json");
    JsonUtility.FromJsonOverwrite(jsonStr, obj);
    Init = true;
}