File size: 1,909 Bytes
6cae93f | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 | using System;
using System.IO;
using UnityEngine;
namespace UnityAgent
{
/// <summary>
/// JSON save system using <see cref="JsonUtility"/>. Stores a single
/// save slot per profile in <c>Application.persistentDataPath</c>.
/// </summary>
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>(T data) where T : class
{
try
{
string json = JsonUtility.ToJson(new Wrapper<T> { 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<T>() where T : class
{
if (!File.Exists(SavePath)) return null;
try
{
string json = File.ReadAllText(SavePath);
var w = JsonUtility.FromJson<Wrapper<T>>(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<T> { public T payload; }
}
}
|