Unity-存储总结

存储常见的几种场景总结:

1 存储和读取基本int, float, string数据。
2 存储和读取字典。
3 存储和读取数组。
4 存储从网络接口拿到的json数据。

using System.Collections;
using System.Collections.Generic;
using System.IO;
using Newtonsoft.Json;
using UnityEngine;


//1 存储和读取基本int, float, string数据。
//2 存储和读取字典。
//3 存储和读取数组。
//4 存储从网络接口拿到的json数据。

public class Demo : MonoBehaviour
{
    //基本int, float, string数据。
    int intData = 0;
    float floatData = 0.0f;
    string stringData = "default";


    Dictionary<int, int> dicData = new Dictionary<int, int>();
    List<int> listData = new List<int>();


    /// <summary>
    /// 模拟的网络接收到的json数据
    /// </summary>
    static string jsonString = @"
            {
                ""a"" : ""a1"",

                ""data"" : {
                    ""b"" : ""b1"",

                    ""year"" : 2002,

                    ""work"" : [
                    ""coder"",
                    ""designer""
                    ],
             
                    ""hobby"" : [{""h1"":""read""}, {""h2"":""run""}],  
                }
            }
        ";

    public class MyModel
    {
        public string a;
        public Data data;
    }

    public class Data
    {
        public string b;
        public int year;
        public string[] work;
        public Hobby[] hobby;
    }

    public class Hobby
    {
        public string h1;
        public string h2;
    }


    void Start()
    {
        Debug.Log($"intData init = {intData}");
        Debug.Log($"floatData init = {floatData}");
        Debug.Log($"stringData init = {stringData}");


        //1 存储和读取基本int, float, string数据。

        SaveData();
        LoadData();


        //2 存储和读取字典。
        dicData.Add(0, 0);
        dicData.Add(1, 1);

        //存储字典,思路是把存储的store当做字典的key,通过这个key再把字典数据读取出来
        PlayerPrefs.SetInt($"dicData{0}_key", dicData[0]);
        //读取字典
        dicData[0] = PlayerPrefs.GetInt($"dicData{0}_key", 0);


        //3 存储和读取数组。

        listData.Add(0);
        listData.Add(1);


        for (int i = 0; i < listData.Count; i++)
        {
            PlayerPrefs.SetInt($"listData{i}_key", listData[i]);
        }

        for (int i = 0; i < listData.Count; i++)
        {
            listData[i] = PlayerPrefs.GetInt($"listData{i}_key", 0);
        }


        //4 存储从网络接口拿到的json数据。
        //把从接口拿到的json数据解析为想要的数据。
        MyModel myModel = GetDataFromJson<MyModel>(jsonString);

        //数据存储成json格式的文件。
        SaveJson(myModel, "json_path", "test.json");

        //将json个格式的文件读取出来,解析成想要的数据
        MyModel myModel2 = LoadJson<MyModel>("json_path", "test.json");

        Debug.Log("myModel2.a = " + myModel2.a);
        Debug.Log("myModel2.data.work[0] = " + myModel2.data.work[0]);
        Debug.Log("myModel2.data.year = " + myModel2.data.year);
        Debug.Log("myModel2.data.hobby[1].h2 = " + myModel2.data.hobby[1].h2);


    }

    public void SaveData()
    {
        intData = 1;
        PlayerPrefs.SetInt("intStore", intData);

        floatData = 1.5f;
        PlayerPrefs.SetFloat("floatStore", floatData);

        stringData = "test";
        PlayerPrefs.SetString("stringStore", stringData);
    }


    public void LoadData()
    {
        intData = PlayerPrefs.GetInt("intStore", 0);
        floatData = PlayerPrefs.GetFloat("floatStore", 0.0f);
        stringData = PlayerPrefs.GetString("stringStore", "default");

        Debug.Log($"intData load = {intData}");
        Debug.Log($"floatData load = {floatData}");
        Debug.Log($"stringData load = {stringData}");
    }



    /// <summary>
    /// 把json字符转换为自己的model数据
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="text"></param>
    /// <returns></returns>
    public static T GetDataFromJson<T>(string text) where T : class
    {
        //JsonConvert类是用的Newtonsoft.Json第三方框架来解析数据,比unity自带JsonUtility处理的数据更复杂些。
        T t = JsonConvert.DeserializeObject<T>(text);
        return t;
    }

    /// <summary>
    /// 保存json数据到本地
    /// </summary>
    /// <param name="jsonTemp"></param>
    //public void SaveJson<T>() where T : class
    void SaveJson<T>(T t, string path, string fileName)
    {
        //如果本地没有对应的json 文件,重新创建
        if (!File.Exists(CreateDirectory(path) + "/" + fileName))
        {
            File.Create(CreateDirectory(path) + "/" + fileName).Dispose();
        }
        string json = JsonConvert.SerializeObject(t);

        File.WriteAllText(CreateDirectory(path) + "/" + fileName, json);
        Debug.Log("Json文件保存成功");

    }

    /// <summary>
    ///  读取本地json文件的数据
    /// </summary>
    /// <param name="dictionarys"></param>
    /// <param name="pathFile"></param>
    public T LoadJson<T>(string path, string fileName) where T : class
    {
        string json = File.ReadAllText(CreateDirectory(path) + "/" + fileName);
        if (string.IsNullOrEmpty(json))
        {
            Debug.LogError("本地json不存在");
            return null;
        }
        T t = JsonConvert.DeserializeObject<T>(json);
        return t;
    }

    /// <summary>
    /// 创建需要保存json文件路径
    /// </summary>
    /// <returns></returns>
    //创建文件夹(路径最后的字符为文件夹)
    public string CreateDirectory(string pathName)
    {

        string path = "";

        if (Application.platform == RuntimePlatform.WindowsEditor)
            path = Application.streamingAssetsPath + "/" + pathName;
        else if (Application.platform == RuntimePlatform.OSXEditor)
            path = Application.streamingAssetsPath + "/" + pathName;
        else if (Application.platform == RuntimePlatform.Android)
            path = Application.persistentDataPath + "/" + pathName;
        else if (Application.platform == RuntimePlatform.IPhonePlayer)
            path = Application.persistentDataPath + "/" + pathName;

        if (!Directory.Exists(path))
            Directory.CreateDirectory(path);

        return path;


    }

}


运行结果
在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值