代码如下,其中形参data一般为ScriptableObject数据:
using System.IO;
using System.Text;
using UnityEngine;
public static class DataManager
{
public static void Save(object data, string url)
{
var jsonData = JsonUtility.ToJson(data, true);
StreamWriter streamWriter = null;
try
{
if (!File.Exists(url))
{
File.Create(url).Dispose();
}
if (File.Exists(url))
{
streamWriter = new StreamWriter(url);
streamWriter.WriteLine(jsonData);
streamWriter.Close();
streamWriter.Dispose();
}
}
catch (System.Exception e)
{
Debug.LogError(e);
}
}
public static void Load(Object data, string url)
{
if (!File.Exists(url))
{
File.Create(url).Dispose();
}
Encoding encoding = Encoding.GetEncoding("utf-8");
StreamReader streamReader = new StreamReader(url, encoding);
string str = streamReader.ReadToEnd();
JsonUtility.FromJsonOverwrite(str, data);
streamReader.Close();
streamReader.Dispose();
}
}