【Unity学习】使用Json文件在本地路径长久储存ScriptableObject数据

代码如下,其中形参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();
    }
}

猜你喜欢

转载自blog.csdn.net/dong89801033/article/details/128665541
今日推荐