| 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); | |
| } | |
| [] | |
| private class Wrapper<T> { public T payload; } | |
| } | |
| } | |