using System;
using System.IO;
using UnityEngine;
namespace GameFramework
{
///
/// 静态 JSON 存档系统。读写 Application.persistentDataPath 下的文件。
/// 排行榜等数据通过它持久化。
///
public static class SaveSystem
{
public static void Save(string saveFileName, object data)
{
var json = JsonUtility.ToJson(data);
var path = Path.Combine(Application.persistentDataPath, saveFileName);
try
{
File.WriteAllText(path, json);
#if UNITY_EDITOR
Debug.Log($"[SaveSystem] 已保存到 {path}");
#endif
}
catch (Exception exception)
{
Debug.LogError($"[SaveSystem] 保存失败 {path}\n{exception}");
}
}
public static T Load(string saveFileName)
{
var path = Path.Combine(Application.persistentDataPath, saveFileName);
try
{
var json = File.ReadAllText(path);
return JsonUtility.FromJson(json);
}
catch (Exception exception)
{
Debug.LogError($"[SaveSystem] 读取失败 {path}\n{exception}");
return default;
}
}
public static void DeleteSaveFile(string saveFileName)
{
var path = Path.Combine(Application.persistentDataPath, saveFileName);
try { File.Delete(path); }
catch (Exception exception) { Debug.LogError($"[SaveSystem] 删除失败 {path}\n{exception}"); }
}
public static bool SaveFileExists(string saveFileName)
{
return File.Exists(Path.Combine(Application.persistentDataPath, saveFileName));
}
}
}