BITKit/Packages/Runtime~/Core/PersistentData/PersistentDataManager.cs

54 lines
1.9 KiB
C#
Raw Normal View History

2023-06-29 14:57:11 +08:00
using System.Collections.Generic;
using System.IO;
2023-06-05 19:57:17 +08:00
using System.Reflection;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
2023-06-29 14:57:11 +08:00
2023-06-05 19:57:17 +08:00
namespace BITKit
{
public class PersistentDataManager
{
static IEnumerable<FieldInfo> fieldInfos=new List<FieldInfo>();
static JObject config;
static string configPath = PathHelper.GetFilePath($"{nameof(config)}.json");
[ExcuteOnAwake]
public static async void Awake()
{
var json = File.ReadAllText( configPath );
if(string.IsNullOrEmpty( json ) is false)
{
config = JObject.Parse(json);
fieldInfos = await ReflectionHelper.GetFields<SaveDataAttribute>();
foreach (var field in fieldInfos)
{
if (config.TryGetValue(field.Name, out var token))
{
var value = token.ToObject(field.FieldType);
BIT4Log.Log<PersistentDataManager>($"正在加载:{field.Name}->{value}");
field.SetValue(null, value);
}
}
}
}
[ExcuteOnStart]
public static void Start()
{
DataParser.Set(File.ReadAllText(configPath));
}
[ExcuteOnStop]
public static void Stop()
{
Dictionary<string,object> dictionary = new Dictionary<string,object>();
foreach (var field in fieldInfos)
{
var value = field.GetValue(null);
dictionary.Add(field.Name,field.GetValue(null));
BIT4Log.Log<PersistentDataManager>($"正在保存:{field.Name}->{value}");
}
var json = JsonConvert.SerializeObject(dictionary);
File.WriteAllText(configPath,json);
BIT4Log.Log<PersistentDataManager>("保存完成");
}
}
}