Unity PC和Android端的数据存储和读取

使用Resource:

提示:使用resouce打包后会被压缩进.resources文件中,意味着它是只读文件,且必须使用resouce.load加载:

    /// <summary>
    /// 全平台使用
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="fileName"></param>
    /// <returns></returns>
    static public T LoadJsonOnResource<T>(string fileName)
    {
        Debug.Log("我是Resources读取");
        string json = "";
        TextAsset text = Resources.Load<TextAsset>("Jsons/" + fileName);
        json = text.text;
        Debug.Log("json: " + json);
        if (string.IsNullOrEmpty(json))
        {
            Debug.LogWarning("this json is null !");
            return default(T);
        }
        T result = JsonUtility.FromJson<T>(json);
        return result;
    }

PC端写入

    /// <summary>
    /// 仅支持Windows平台写入
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="path"></param>
    /// <param name="fileName"></param>
    /// <param name="info"></param>
    static public void SaveJsonOnWin<T>(PathType path, string fileName, T info)
    {
        string url = "";
        if (path == PathType.ResourcePath)
        {
            url = Application.dataPath + "/Resources/Jsons/" + fileName;
        }
        else if (path == PathType.StreamingAssetsPath)
        {
            url = Application.streamingAssetsPath + "/" + fileName;
        }
        else
        {
            url = Application.dataPath + "/" + fileName;
        }

        Debug.Log("url:     " + url);

        if (File.Exists(url))
        {
            File.Delete(url);
        }

        File.Create(url).Dispose();//这里不加dispose会报错,很重要
        string json = JsonUtility.ToJson(info);
        Debug.Log("json: " + json);
        try
        {
            StreamWriter sw = new StreamWriter(url);
            sw.WriteLine(json);
            sw.Close();
            Debug.Log("写入成功");
        }
        catch (Exception)
        {
            Debug.Log("json出错");
        }
    }

PC端读取:

    static public T LoadJsonOnWinPath<T>(PathType path, string fileName)
    {
        string url = "";
        if (path == PathType.StreamingAssetsPath)
        {
            url = Application.streamingAssetsPath + "/" + fileName;
            Debug.Log("我是StreamingAssetsPath读取\n" + url);
        }
        else
        {
            url = Application.dataPath + "/" + fileName;
            Debug.Log("我是NormalPath读取\n" + url);
        }
        if (!File.Exists(url))
        {
            Debug.LogWarning("path is null !     " + fileName);
            return default(T);
        }
        StreamReader sr = new StreamReader(url);
        string json = sr.ReadToEnd();
        Debug.Log("json: " + json);
        T result = default(T);
        if (!string.IsNullOrEmpty(json))
        {
            result = JsonUtility.FromJson<T>(json);
        }
        sr.Close();
        return result;
    }

Android端写入:

提示: PersistentDataPath使用该路径写入

    /// <summary>
    /// android平台只有该路径支持写入
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="path"></param>
    /// <param name="fileName"></param>
    /// <param name="info"></param>
    static public void SaveJsonOnAndroid<T>(string fileName, T info)
    {
        string url = Path.Combine(Application.persistentDataPath, fileName);

        Debug.Log("我是PersistentDataPath存储\n" + url);
        StreamWriter sw = null;
        if (!File.Exists(url))
        {
            sw = File.CreateText(url);
        }
        string json = JsonUtility.ToJson(info);
        Debug.Log("json: " + json);
        sw.WriteLine(json);
        sw.Close();
    }

Android端读取:

    static public T LoadJsonOnAndroid<T>(PathType path, string file)
    {
        string url = "";
 		if (path == PathType.PersistentDataPath)
        {
            url = Application.persistentDataPath + "/" + file;
            Debug.Log("我是PersistentDataPath读取\n" + url);
        }

        string json = "";
        if (File.Exists(url))
        {
            try
            {
                FileStream fileStream = new FileStream(url, FileMode.OpenOrCreate);
                StreamReader sr = new StreamReader(fileStream, Encoding.UTF8);
                json = sr.ReadToEnd();
                Debug.Log("fileStream   json: " + json);
                T result = default(T);
                if (!string.IsNullOrEmpty(json))
                {
                    result = JsonUtility.FromJson<T>(json);
                }
                sr.Close();
                return result;
            }
            catch
            {
                Debug.LogFormat("url:   {0} error or stream error", url);
            }
        }
        else
        {
            Debug.LogError("file not exist  " + url);
        }
        return default(T);
    }

注意:Android端的StreamingAssets读取不能使用该方法读取。

最后附上完整代码

using System;
using System.IO;
using System.Text;
using UnityEngine;
using Debug = UnityEngine.Debug;
public class JsonExtension
{
    /// <summary>
    /// 全平台使用
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="fileName"></param>
    /// <returns></returns>
    static public T LoadJsonOnResource<T>(string fileName)
    {
        Debug.Log("我是Resources读取");
        string json = "";
        TextAsset text = Resources.Load<TextAsset>("Jsons/" + fileName);
        json = text.text;
        Debug.Log("json: " + json);
        if (string.IsNullOrEmpty(json))
        {
            Debug.LogWarning("this is jsons is null !");
            return default(T);
        }
        T result = JsonUtility.FromJson<T>(json);
        return result;
    }

    /// <summary>
    /// 仅支持Windows平台写入
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="path"></param>
    /// <param name="fileName"></param>
    /// <param name="info"></param>
    static public void SaveJsonOnWin<T>(PathType path, string fileName, T info)
    {
        string url = "";
        if (path == PathType.ResourcePath)
        {
            url = Application.dataPath + "/Resources/Jsons/" + fileName;
        }
        else if (path == PathType.StreamingAssetsPath)
        {
            url = Application.streamingAssetsPath + "/" + fileName;
        }
        else
        {
            url = Application.dataPath + "/" + fileName;
        }

        Debug.Log("url:     " + url);

        if (File.Exists(url))
        {
            File.Delete(url);
        }

        File.Create(url).Dispose();
        string json = JsonUtility.ToJson(info);
        Debug.Log("json: " + json);
        try
        {
            StreamWriter sw = new StreamWriter(url);
            sw.WriteLine(json);
            sw.Close();
            Debug.Log("写入成功");
        }
        catch (Exception)
        {
            Debug.Log("json出错");
        }
        //sw.Flush();

        //FileStream fs = new FileStream(url, FileMode.OpenOrCreate);
        //byte[] byteArray = Encoding.UTF8.GetBytes(info);
        //foreach (var by in byteArray)
        //{
        //    fs.WriteByte(by);
        //}
    }

    static public T LoadJsonOnWinPath<T>(PathType path, string fileName)
    {
        string url = "";
        if (path == PathType.StreamingAssetsPath)
        {
            url = Application.streamingAssetsPath + "/" + fileName;
            Debug.Log("我是StreamingAssetsPath读取\n" + url);
        }
        else
        {
            url = Application.dataPath + "/" + fileName;
            Debug.Log("我是NormalPath读取\n" + url);
        }
        if (!File.Exists(url))
        {
            Debug.LogWarning("path is null !     " + fileName);
            return default(T);
        }
        StreamReader sr = new StreamReader(url);
        string json = sr.ReadToEnd();
        Debug.Log("json: " + json);
        T result = default(T);
        if (!string.IsNullOrEmpty(json))
        {
            result = JsonUtility.FromJson<T>(json);
        }
        sr.Close();
        return result;
    }

    /// <summary>
    /// android平台只有该路径支持写入
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="path"></param>
    /// <param name="fileName"></param>
    /// <param name="info"></param>
    static public void SaveJsonOnAndroid<T>(string fileName, T info)
    {
        string url = Path.Combine(Application.persistentDataPath, fileName);

        Debug.Log("我是PersistentDataPath存储\n" + url);
        StreamWriter sw = null;
        if (!File.Exists(url))
        {
            sw = File.CreateText(url);
        }
        string json = JsonUtility.ToJson(info);
        Debug.Log("json: " + json);
        sw.WriteLine(json);
        sw.Close();
    }

    static public T LoadJsonOnAndroid<T>(PathType path, string file)
    {
        string url = "";
        if (path == PathType.PersistentDataPath)
        {
            url = Application.persistentDataPath + "/" + file;
            Debug.Log("我是PersistentDataPath读取\n" + url);
        }

        string json = "";
        if (File.Exists(url))
        {
            try
            {
                FileStream fileStream = new FileStream(url, FileMode.OpenOrCreate);
                StreamReader sr = new StreamReader(fileStream, Encoding.UTF8);
                json = sr.ReadToEnd();
                Debug.Log("fileStream   json: " + json);
                T result = default(T);
                if (!string.IsNullOrEmpty(json))
                {
                    result = JsonUtility.FromJson<T>(json);
                }
                sr.Close();
                return result;
            }
            catch
            {
                Debug.LogFormat("url:   {0} error or stream error", url);
            }
        }
        else
        {
            Debug.LogError("file not exist  " + url);
        }
        return default(T);
    }

    public enum PathType
    {
        ResourcePath,
        StreamingAssetsPath,
        PersistentDataPath,
        NormalPath
    }
}

using System;
using System.Collections;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.UI;

public class TestJson : MonoBehaviour
{
    #region Windows
    public Button btn1;
    public Button btn2;
    public Button btn3;
    public Button btn4;
    #endregion

    #region Android
    public Button btn5;
    public Button btn6;
    public Button btn7;
    public Button btn8;
    #endregion

    public GameObject[] WinBtns;
    public GameObject[] AndroidBtns;
    void Start()
    {
        MyJsonData data1 = new MyJsonData(10, "alibaba", Vector3.one);
        MyJsonData data2 = new MyJsonData(20, "tx", Vector3.one);

        if (Application.platform == RuntimePlatform.WindowsEditor || Application.platform == RuntimePlatform.WindowsPlayer)
        {
            for (int i = 0; i < WinBtns.Length; i++)
            {
                WinBtns[i].gameObject.SetActive(true);
            }
            btn1.onClick.AddListener(() =>
            {
                JsonExtension.SaveJsonOnWin(JsonExtension.PathType.ResourcePath, "test1.json", data1);
            });

            btn2.onClick.AddListener(() =>
            {
                JsonExtension.SaveJsonOnWin(JsonExtension.PathType.StreamingAssetsPath, "test2.json", data1);
            });

            btn3.onClick.AddListener(() =>
            {
                JsonExtension.LoadJsonOnResource<MyJsonData>("test1");
            });

            btn4.onClick.AddListener(() =>
            {
                JsonExtension.LoadJsonOnWinPath<MyJsonData>(JsonExtension.PathType.StreamingAssetsPath, "test2.json");
            });
        }
        if (Application.platform == RuntimePlatform.Android)
        {
            for (int i = 0; i < AndroidBtns.Length; i++)
            {
                AndroidBtns[i].gameObject.SetActive(true);
            }

            btn5.onClick.AddListener(() =>
            {
                JsonExtension.SaveJsonOnAndroid("test3.json", data2);
            });

            btn6.onClick.AddListener(() =>
            {
                JsonExtension.LoadJsonOnResource<MyJsonData>("test1");
            });

            btn7.onClick.AddListener(() =>
            {
                //直接读会报错,必须使用UnityWebRequest读取
                //je.LoadJsonOnAndroid<MyJsonData>(JsonExtension.PathType.StreamingAssetsPath, "test2.json");
                StartCoroutine(LoadFromStreamingAssets(Application.streamingAssetsPath + "/test2.json"));
            });

            btn8.onClick.AddListener(() =>
            {
                JsonExtension.LoadJsonOnAndroid<MyJsonData>(JsonExtension.PathType.PersistentDataPath, "test3.json");
            });
        }

    }

    IEnumerator LoadFromStreamingAssets(string url)
    {
        using (UnityWebRequest request = UnityWebRequest.Get(url))
        {
            yield return request.SendWebRequest();
            if (request.isDone)
            {
                if (request.isNetworkError || request.isHttpError)
                {
                    Debug.Log(request.error);
                }
                else
                {
                    Debug.Log("我是UnityWebRequest读取安卓");
                    string androidJson = request.downloadHandler.text;
                    Debug.Log("androidJson: " + androidJson);
                    /*
                     * 对json做处理
                     */
                }
            }
        }
    }
}

[Serializable]
public class MyJsonData
{
    public int id;
    public string name;
    public Vector3 pos;

    public MyJsonData(int id, string name, Vector3 pos)
    {
        this.id = id;
        this.name = name;
        this.pos = pos;
    }
}
  • 8
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值