using System;
using System.IO;
using UnityEngine;
namespace UnityAgent
{
///
/// JSON save system using . Stores a single
/// save slot per profile in Application.persistentDataPath.
///
public class SaveSystem : MonoBehaviour
{
public static SaveSystem Instance { get; private set; }
public string profileName = "default";
private void Awake()
{
if (Instance != null && Instance != this) { Destroy(gameObject); return; }
Instance = this;
DontDestroyOnLoad(gameObject);
}
private string SavePath => Path.Combine(Application.persistentDataPath, profileName + ".save");
public void Save(T data) where T : class
{
try
{
string json = JsonUtility.ToJson(new Wrapper { payload = data }, true);
File.WriteAllText(SavePath, json);
Debug.Log($"[SaveSystem] Saved to {SavePath}");
}
catch (Exception e)
{
Debug.LogError($"[SaveSystem] Save failed: {e}");
}
}
public T Load() where T : class
{
if (!File.Exists(SavePath)) return null;
try
{
string json = File.ReadAllText(SavePath);
var w = JsonUtility.FromJson>(json);
return w?.payload;
}
catch (Exception e)
{
Debug.LogError($"[SaveSystem] Load failed: {e}");
return null;
}
}
public bool HasSave => File.Exists(SavePath);
public void Delete()
{
if (File.Exists(SavePath)) File.Delete(SavePath);
}
[Serializable]
private class Wrapper { public T payload; }
}
}