unity 本地缓存数据

 用到json插件LitJson

using System.Collections.Generic;
using UnityEngine;

namespace NxFish {
    public sealed class SaveDataManager : Singleton<SaveDataManager> {
      

        public bool IsDirty { get; private set; }

        private Dictionary<string, object> data;

        public bool HasKey(string key) {
            return this.data.ContainsKey(key);
        }

        public T Get<T>(string key, T defaultValue) {
            return this.HasKey(key) ? (T) this.data[key] : defaultValue;
        }

        public void Set<T>(string key, T value) {
            if (this.HasKey(key)) {
                this.data[key] = value;
            } else {
                this.data.Add(key, value);
            }
            this.IsDirty = true;
        }

        public void Delete(string key) {
            if (this.HasKey(key)) {
                this.data.Remove(key);
            }
            this.IsDirty = true;
        }

        public void Save() {
            string json = LitJson.JsonMapper.ToJson(this.data);
            //加密?
            //json = Utils.EncryptLocal(json);
            PlayerPrefs.SetString("SaveData", json);
            PlayerPrefs.Save();
            this.IsDirty = false;
        }

        public void Load() {
            //this.Clear();
            string json = PlayerPrefs.GetString("SaveData", "");
            if (json.Length > 0) {
                //解密?
                //if (!json.StartsWith("{")) {
                //    json = Utils.DecryptLocal(json);
                //}

                this.data = LitJson.JsonMapper.ToObject<Dictionary<string, object>>(json);
            }

            if (this.data == null) {
                this.data = new Dictionary<string, object>();
            }

            this.IsDirty = false;
        }

        public void Clear() {
            this.data?.Clear();
            PlayerPrefs.DeleteAll();
            PlayerPrefs.Save();
            this.IsDirty = false;
        }
    }
}

游戏开始时全局控制脚本里加载:

   Singleton<SaveDataManager>.Instance.Load();
using UnityEngine;
using System.Collections.Generic;
using System.Text;
using System.Linq;

namespace NxFish.Data {
    public struct MailGiftData {
        public string id;
        public string num;
        public string name;
    }
    public sealed class MailDetail {
        public string id;
        public string title;
        public string endTime;
        public string content;
        public string type;
        public readonly List<MailGiftData> giftList =new List<MailGiftData>();
    }

    public sealed class MailItemData {
        public string user_id;
        public string id;
        public string title;
        public string startTime;
        public int isread;
        public int isgain;
        public int type;
        public MailDetail detail;
    }

  

    
    public class MailUIData : MonoBehaviour{
     
        public List<MailItemData> mailDatas = new List<MailItemData>();
     
        /// <summary>
        /// 字段值判空
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public static string CheckJsonDataNull(JsonData data) {
            if (data != null) {
                return data.ToString();
            }
            return string.Empty;
        }

        public string listKey = "EmailDataCacheKey";
        public void Save() {
            string userId = GameController.Instance.account.id;
            if (this.mailDatasCacheDic.ContainsKey(userId)) {
                this.mailDatasCacheDic[userId]=this.mailDatasCache;
            } else {
                this.mailDatasCacheDic.Add(userId, this.mailDatasCache);
            }

            SaveDataManager saveMgr = Singleton<SaveDataManager>.Instance;
            if (saveMgr != null) {
                saveMgr.Set(listKey, this.ToLocalJson());
                saveMgr.Save();
            }
        }

        public List<MailItemData> mailDatasCache = new List<MailItemData>();
        public Dictionary<string, List<MailItemData>> mailDatasCacheDic = new Dictionary<string, List<MailItemData>>();
        private string ToLocalJson() {
            StringBuilder sb = new StringBuilder();
            LitJson.JsonWriter writer = new LitJson.JsonWriter(sb);
            writer.WriteObjectStart();
            {
                writer.WritePropertyName("EmailDataCache");
                string data = LitJson.JsonMapper.ToJson(this.mailDatasCacheDic);
                Debug.Log(data);
                writer.Write(data ?? "{}");

            }
            writer.WriteObjectEnd();

            return sb.ToString();
        }

        public bool Load() {
            string json = Singleton<SaveDataManager>.Instance.Get(listKey, "");
            if (string.IsNullOrEmpty(json)) {
                return false;
            }
            Debug.Log(json);
            this.FromLocalJson(json);
            return true;
        }

        private void FromLocalJson(string json) {
            LitJson.JsonData _data = LitJson.JsonMapper.ToObject(json);
            if (_data.Keys.Contains("EmailDataCache")) {
                string check = CheckJsonDataNull(_data["EmailDataCache"]);
                if (string.IsNullOrEmpty(check)) return;

                LitJson.JsonData data = _data["EmailDataCache"];
                if (_data["EmailDataCache"] == null) return;

                this.mailDatasCacheDic= LitJson.JsonMapper.ToObject<Dictionary<string, List<MailItemData>>>(data.ToString());

                this.mailDatasCache.Clear();
                string use_id = GameController.Instance.account.id;
                if (this.mailDatasCacheDic.ContainsKey(use_id)) {
                    this.mailDatasCache.AddRange(this.mailDatasCacheDic[use_id]);
                }

            }
        }
    }
}

外部加载:

   if (this.mailData.Load()) {
          //TODO
   }

外部保存:直接调用Save() 方法

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值