MayHeCome/Assets/Scripts/SaveSystem.cs
2024-12-18 17:55:34 +08:00

74 lines
2.2 KiB
C#

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Cysharp.Threading.Tasks;
using Newtonsoft.Json;
using UnityEngine;
public class SaveSystem: Singleton<SaveSystem>
{
public int SaveSlot = 0;
public string savePath => Path.Combine(Application.persistentDataPath, $"Save_{SaveSlot}.json");
// public async UniTaskVoid SaveConfig()
// {
//
// }
//
// public async UniTaskVoid LoadConfig()
// {
//
// }
public async UniTaskVoid Save()
{
var finalSave = new Dictionary<string, Dictionary<string, string>>();
var savables = FindObjectsOfType<MonoBehaviour>().OfType<ISavable>();
foreach (var savable in savables)
{
var path = savable.GetPath();
if (finalSave.ContainsKey(path))
{
Debug.LogError($"存档中{path}这个键已经存在了,请确保你当前这个保存物体在场景中的同层级下的是独一无二的");
continue;
}
finalSave[path] = savable.SaveData();
}
FileStream stream = new(savePath, FileMode.Create);
byte[] bytes = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(finalSave));
await stream.WriteAsync(bytes);
stream.Close();
await stream.DisposeAsync();
Debug.Log("Save Finish");
}
public async UniTaskVoid Load()
{
_ = BlobManager.Instance;
await UniTask.NextFrame();
using (System.IO.StreamReader file = System.IO.File.OpenText(savePath))
{
var saveString = await file.ReadToEndAsync();
var saveData = JsonConvert.DeserializeObject<Dictionary<string, Dictionary<string, string>>>(saveString);
foreach (var (path, data) in saveData)
{
ISavable savable = GameObject.Find(path).GetComponent<ISavable>();
if (savable != null)
{
savable.LoadData(data);
}
else
{
Debug.LogError($"找不到物体{path}.");
}
}
}
Debug.Log("Load Finish");
}
}