54 lines
1.9 KiB
C#
54 lines
1.9 KiB
C#
using System.Collections.Generic;
|
|
using System.IO;
|
|
using System.Reflection;
|
|
using Newtonsoft.Json;
|
|
using Newtonsoft.Json.Linq;
|
|
|
|
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>("保存完成");
|
|
}
|
|
}
|
|
}
|