using System; using System.Collections.Generic; using System.Linq; using UnityEngine; namespace Guru { [Serializable] internal class RemoteConfigModel { private static float SaveInterval = 2f; private const string SaveKey = "comr.guru.remote.model.save"; public Dictionary configs; public long last_modified = 0; private float _lastSavedTime = 0; /// /// 创建或加载 /// /// public static RemoteConfigModel LoadOrCreate() { RemoteConfigModel model = null; if (PlayerPrefs.HasKey(SaveKey)) { string json = LoadStringValue(SaveKey); model = JsonParser.ToObject(json); } if (model == null) model = new RemoteConfigModel(); return model; } /// /// 默认赋值数据 /// private Dictionary _defConfigs; /// /// 加载数据 /// /// /// /// private static string LoadStringValue(string key, string defaultValue = "") { if (PlayerPrefs.HasKey(key)) { return PlayerPrefs.GetString(key, defaultValue); } return defaultValue; } /// /// 保存数据 /// /// /// private static void SaveToPlayerPrefs(string key, string value) { PlayerPrefs.SetString(key, value); } /// /// 初始化 /// public RemoteConfigModel() { _defConfigs = new Dictionary(20); configs = new Dictionary(20); } /// /// 是否有数据 /// /// /// public bool HasKey(string key) => configs.ContainsKey(key); /// /// 保存数据 /// /// public void Save(bool forceSave = false) { if (forceSave || (Time.realtimeSinceStartup - _lastSavedTime > SaveInterval)) { _lastSavedTime = Time.realtimeSinceStartup; last_modified = TimeUtil.GetCurrentTimeStamp(); SaveToPlayerPrefs(SaveKey, JsonParser.ToJson(this)); } } /// /// 设置默认值 /// /// /// public void SetDefaultConfig(string key, string value) { _defConfigs[key] = value; if (!HasKey(key)) { SetConfigValue(key, value); } } /// /// 设置当前值 /// /// /// public void SetDefaultConfig(string key, T config) where T : IRemoteConfig { var json = config.ToJson(); SetDefaultConfig(key, json); } /// /// 获取配置对象 /// /// /// /// public T Get(string key) where T : IRemoteConfig { string json = ""; if (HasKey(key)) { json = configs[key]; } else if (_defConfigs.TryGetValue(key, out var defValue)) { json = defValue; } if (!string.IsNullOrEmpty(json)) { return JsonParser.ToObject(json); } Log.E(RemoteConfigManager.Tag, $" --- Remote Key {key} has never been registered."); return default(T); } /// /// 设置对象值 /// /// /// /// internal void SetConfigValue(string key, string value) { configs[key] = value; Save(); } /// /// 更新所有的配置 /// /// public void UpdateConfigs(Dictionary updates) { string key, value; for (int i = 0; i < updates.Keys.Count; i++) { key = updates.Keys.ElementAt(i); value = updates.Values.ElementAt(i); if (!HasKey(key) || configs[key] != value) { // New Key or Value Changed configs[key] = value; } } Save(true); // 直接保存 } } }