save a scriptable object to js9n file in csharp

To save a Scriptable Object to a JSON file in C#, you will need to use the JsonUtility class provided by Unity. Here’s an example of how to do it:

main.cs
using UnityEngine;
using System.IO;

public class SaveSOToJson : MonoBehaviour
{
    public MyScriptableObject myScriptableObj;
    public string fileName = "mySO.json";
    
    public void Save()
    {
        string json = JsonUtility.ToJson(myScriptableObj);
        string path = Path.Combine(Application.streamingAssetsPath, fileName);
        File.WriteAllText(path, json);
        Debug.Log("Scriptable Object saved to " + path);
    }
}
446 chars
17 lines

In the example above, we have a public field myScriptableObj that is the Scriptable Object we want to save, and a public string field fileName that is the name of the file we want to save to. We also have a public method Save() that does the actual saving.

In the Save() method, we first use JsonUtility.ToJson() to convert the Scriptable Object to a JSON string. We then use Path.Combine() to create a full file path by combining the Application.streamingAssetsPath and fileName fields. Finally, we use File.WriteAllText() to write the JSON string to the file at the path we just created.

That's it! Now you can call the Save() method wherever you need to save your Scriptable Object to a JSON file.

gistlibby LogSnag