1
This commit is contained in:
56
Packages/Core/PersistentData/PersistentDataManager.cs
Normal file
56
Packages/Core/PersistentData/PersistentDataManager.cs
Normal file
@@ -0,0 +1,56 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using System.Reflection;
|
||||
using Newtonsoft.Json;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using System.IO;
|
||||
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>("保存完成");
|
||||
}
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user