From 614a60b4b3ba41f3ea1d8bad6ec560ce10cd8907 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=9D=D0=B0=D0=B7=D0=B0=D1=80?= Date: Mon, 27 Jul 2026 21:16:47 +0300 Subject: [PATCH 01/19] chore: add persistence runtime folder --- Assets/_ZoneUA/Runtime/Persistence.meta | 8 ++++++++ 1 file changed, 8 insertions(+) create mode 100644 Assets/_ZoneUA/Runtime/Persistence.meta diff --git a/Assets/_ZoneUA/Runtime/Persistence.meta b/Assets/_ZoneUA/Runtime/Persistence.meta new file mode 100644 index 0000000..9b72e8a --- /dev/null +++ b/Assets/_ZoneUA/Runtime/Persistence.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 53fd351065874dfaa36ce05250b7bdc3 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: From bea0949a29e3d5583f112464b919592de0ea9973 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=9D=D0=B0=D0=B7=D0=B0=D1=80?= Date: Mon, 27 Jul 2026 21:16:56 +0300 Subject: [PATCH 02/19] feat: add persistence runtime assembly --- .../Runtime/Persistence/ZoneUA.Persistence.asmdef | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 Assets/_ZoneUA/Runtime/Persistence/ZoneUA.Persistence.asmdef diff --git a/Assets/_ZoneUA/Runtime/Persistence/ZoneUA.Persistence.asmdef b/Assets/_ZoneUA/Runtime/Persistence/ZoneUA.Persistence.asmdef new file mode 100644 index 0000000..c24462a --- /dev/null +++ b/Assets/_ZoneUA/Runtime/Persistence/ZoneUA.Persistence.asmdef @@ -0,0 +1,14 @@ +{ + "name": "ZoneUA.Persistence", + "rootNamespace": "ZoneUA.Persistence", + "references": [], + "includePlatforms": [], + "excludePlatforms": [], + "allowUnsafeCode": false, + "overrideReferences": false, + "precompiledReferences": [], + "autoReferenced": true, + "defineConstraints": [], + "versionDefines": [], + "noEngineReferences": false +} From 5da2e7ef594cc5529c26ad4c0dcedd25b6bfc3f5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=9D=D0=B0=D0=B7=D0=B0=D1=80?= Date: Mon, 27 Jul 2026 21:17:07 +0300 Subject: [PATCH 03/19] chore: add persistence asmdef meta --- .../Runtime/Persistence/ZoneUA.Persistence.asmdef.meta | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 Assets/_ZoneUA/Runtime/Persistence/ZoneUA.Persistence.asmdef.meta diff --git a/Assets/_ZoneUA/Runtime/Persistence/ZoneUA.Persistence.asmdef.meta b/Assets/_ZoneUA/Runtime/Persistence/ZoneUA.Persistence.asmdef.meta new file mode 100644 index 0000000..cea57b5 --- /dev/null +++ b/Assets/_ZoneUA/Runtime/Persistence/ZoneUA.Persistence.asmdef.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 4b7ec35f64344d0e95ab7974b1233e5c +AssemblyDefinitionImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: From 4e529a44cb733bd978bb57f10ec16dd6be35d7dd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=9D=D0=B0=D0=B7=D0=B0=D1=80?= Date: Mon, 27 Jul 2026 21:17:22 +0300 Subject: [PATCH 04/19] feat: add versioned save game schema --- .../Runtime/Persistence/SaveGameData.cs | 36 +++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 Assets/_ZoneUA/Runtime/Persistence/SaveGameData.cs diff --git a/Assets/_ZoneUA/Runtime/Persistence/SaveGameData.cs b/Assets/_ZoneUA/Runtime/Persistence/SaveGameData.cs new file mode 100644 index 0000000..4eafc5d --- /dev/null +++ b/Assets/_ZoneUA/Runtime/Persistence/SaveGameData.cs @@ -0,0 +1,36 @@ +using System; +using UnityEngine; + +namespace ZoneUA.Persistence +{ + [Serializable] + public sealed class SaveGameData + { + public const int CurrentSchemaVersion = 2; + + public int schemaVersion = CurrentSchemaVersion; + public string saveId = string.Empty; + public string savedAtUtc = string.Empty; + public string activeScene = string.Empty; + public int worldSeed; + public PlayerSaveData player = new PlayerSaveData(); + + public void Stamp(string id, DateTime utcNow) + { + schemaVersion = CurrentSchemaVersion; + saveId = id ?? string.Empty; + savedAtUtc = utcNow.ToUniversalTime().ToString("O"); + player ??= new PlayerSaveData(); + } + } + + [Serializable] + public sealed class PlayerSaveData + { + public Vector3 position; + public float rotationZ; + public int currentHealth = 100; + public int maximumHealth = 100; + public int activeWeaponIndex = -1; + } +} From 40512a24387a6293d4ddd8a59f66922f6b7c3327 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=9D=D0=B0=D0=B7=D0=B0=D1=80?= Date: Mon, 27 Jul 2026 21:17:33 +0300 Subject: [PATCH 05/19] chore: add save schema meta --- .../_ZoneUA/Runtime/Persistence/SaveGameData.cs.meta | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 Assets/_ZoneUA/Runtime/Persistence/SaveGameData.cs.meta diff --git a/Assets/_ZoneUA/Runtime/Persistence/SaveGameData.cs.meta b/Assets/_ZoneUA/Runtime/Persistence/SaveGameData.cs.meta new file mode 100644 index 0000000..623ac49 --- /dev/null +++ b/Assets/_ZoneUA/Runtime/Persistence/SaveGameData.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 18f27aa5b38d4be9904bb7dc4b72c6a0 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: From 3fb6a07c0e3938358bd597c889b8609a840d9a4f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=9D=D0=B0=D0=B7=D0=B0=D1=80?= Date: Mon, 27 Jul 2026 21:17:46 +0300 Subject: [PATCH 06/19] feat: add save schema migration --- .../Runtime/Persistence/SaveGameMigrator.cs | 27 +++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 Assets/_ZoneUA/Runtime/Persistence/SaveGameMigrator.cs diff --git a/Assets/_ZoneUA/Runtime/Persistence/SaveGameMigrator.cs b/Assets/_ZoneUA/Runtime/Persistence/SaveGameMigrator.cs new file mode 100644 index 0000000..942d4ae --- /dev/null +++ b/Assets/_ZoneUA/Runtime/Persistence/SaveGameMigrator.cs @@ -0,0 +1,27 @@ +using System; + +namespace ZoneUA.Persistence +{ + public static class SaveGameMigrator + { + public static SaveGameData Migrate(SaveGameData data) + { + if (data == null) throw new ArgumentNullException(nameof(data)); + if (data.schemaVersion <= 0) data.schemaVersion = 1; + if (data.schemaVersion > SaveGameData.CurrentSchemaVersion) + throw new InvalidOperationException($"Save schema {data.schemaVersion} is newer than supported schema {SaveGameData.CurrentSchemaVersion}."); + + if (data.schemaVersion == 1) + { + data.player ??= new PlayerSaveData(); + if (data.player.maximumHealth <= 0) data.player.maximumHealth = Math.Max(1, data.player.currentHealth); + data.schemaVersion = 2; + } + + data.player ??= new PlayerSaveData(); + data.player.maximumHealth = Math.Max(1, data.player.maximumHealth); + data.player.currentHealth = Math.Clamp(data.player.currentHealth, 0, data.player.maximumHealth); + return data; + } + } +} From ec99274ea7c008bb364f5eda906eac32a07663a7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=9D=D0=B0=D0=B7=D0=B0=D1=80?= Date: Mon, 27 Jul 2026 21:17:56 +0300 Subject: [PATCH 07/19] chore: add save migrator meta --- .../Runtime/Persistence/SaveGameMigrator.cs.meta | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 Assets/_ZoneUA/Runtime/Persistence/SaveGameMigrator.cs.meta diff --git a/Assets/_ZoneUA/Runtime/Persistence/SaveGameMigrator.cs.meta b/Assets/_ZoneUA/Runtime/Persistence/SaveGameMigrator.cs.meta new file mode 100644 index 0000000..6162c92 --- /dev/null +++ b/Assets/_ZoneUA/Runtime/Persistence/SaveGameMigrator.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 93d3f03654ac491da63aa6d7c5cd9d74 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: From afa103217936aaf418577ff6ecf05cdd8c08b5ba Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=9D=D0=B0=D0=B7=D0=B0=D1=80?= Date: Mon, 27 Jul 2026 21:18:14 +0300 Subject: [PATCH 08/19] feat: add atomic save slot storage --- .../Runtime/Persistence/SaveSlotStore.cs | 101 ++++++++++++++++++ 1 file changed, 101 insertions(+) create mode 100644 Assets/_ZoneUA/Runtime/Persistence/SaveSlotStore.cs diff --git a/Assets/_ZoneUA/Runtime/Persistence/SaveSlotStore.cs b/Assets/_ZoneUA/Runtime/Persistence/SaveSlotStore.cs new file mode 100644 index 0000000..6170616 --- /dev/null +++ b/Assets/_ZoneUA/Runtime/Persistence/SaveSlotStore.cs @@ -0,0 +1,101 @@ +using System; +using System.IO; +using System.Security.Cryptography; +using System.Text; +using UnityEngine; + +namespace ZoneUA.Persistence +{ + [Serializable] + public sealed class SaveEnvelope + { + public string checksum = string.Empty; + public string payload = string.Empty; + } + + public sealed class SaveSlotStore + { + private readonly string rootDirectory; + + public SaveSlotStore(string rootDirectory) + { + this.rootDirectory = string.IsNullOrWhiteSpace(rootDirectory) + ? throw new ArgumentException("A save root directory is required.", nameof(rootDirectory)) + : rootDirectory; + } + + public string GetSlotPath(string slotId) => Path.Combine(rootDirectory, Sanitize(slotId) + ".json"); + public string GetBackupPath(string slotId) => GetSlotPath(slotId) + ".bak"; + + public void Save(string slotId, SaveGameData data) + { + if (data == null) throw new ArgumentNullException(nameof(data)); + Directory.CreateDirectory(rootDirectory); + + string payload = JsonUtility.ToJson(data, false); + var envelope = new SaveEnvelope { payload = payload, checksum = ComputeChecksum(payload) }; + string serialized = JsonUtility.ToJson(envelope, true); + string path = GetSlotPath(slotId); + string temp = path + ".tmp"; + string backup = GetBackupPath(slotId); + + File.WriteAllText(temp, serialized, Encoding.UTF8); + if (File.Exists(path)) File.Copy(path, backup, true); + if (File.Exists(path)) File.Delete(path); + File.Move(temp, path); + } + + public bool TryLoad(string slotId, out SaveGameData data) + { + if (TryLoadPath(GetSlotPath(slotId), out data)) return true; + return TryLoadPath(GetBackupPath(slotId), out data); + } + + public bool Exists(string slotId) => File.Exists(GetSlotPath(slotId)) || File.Exists(GetBackupPath(slotId)); + + public void Delete(string slotId) + { + DeleteIfExists(GetSlotPath(slotId)); + DeleteIfExists(GetBackupPath(slotId)); + DeleteIfExists(GetSlotPath(slotId) + ".tmp"); + } + + private static bool TryLoadPath(string path, out SaveGameData data) + { + data = null; + if (!File.Exists(path)) return false; + try + { + SaveEnvelope envelope = JsonUtility.FromJson(File.ReadAllText(path, Encoding.UTF8)); + if (envelope == null || string.IsNullOrEmpty(envelope.payload)) return false; + if (!string.Equals(envelope.checksum, ComputeChecksum(envelope.payload), StringComparison.OrdinalIgnoreCase)) return false; + data = SaveGameMigrator.Migrate(JsonUtility.FromJson(envelope.payload)); + return data != null; + } + catch + { + data = null; + return false; + } + } + + private static string ComputeChecksum(string value) + { + using SHA256 sha = SHA256.Create(); + byte[] bytes = sha.ComputeHash(Encoding.UTF8.GetBytes(value ?? string.Empty)); + return Convert.ToHexString(bytes); + } + + private static string Sanitize(string slotId) + { + string value = string.IsNullOrWhiteSpace(slotId) ? "autosave" : slotId.Trim(); + foreach (char invalid in Path.GetInvalidFileNameChars()) value = value.Replace(invalid, '_'); + return value; + } + + private static void DeleteIfExists(string path) + { + if (File.Exists(path)) File.Delete(path); + } + } +} From f86106f9ecf9212a57316c567d0c9b4b3a238f5c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=9D=D0=B0=D0=B7=D0=B0=D1=80?= Date: Mon, 27 Jul 2026 21:18:23 +0300 Subject: [PATCH 09/19] chore: add save slot store meta --- .../_ZoneUA/Runtime/Persistence/SaveSlotStore.cs.meta | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 Assets/_ZoneUA/Runtime/Persistence/SaveSlotStore.cs.meta diff --git a/Assets/_ZoneUA/Runtime/Persistence/SaveSlotStore.cs.meta b/Assets/_ZoneUA/Runtime/Persistence/SaveSlotStore.cs.meta new file mode 100644 index 0000000..552c872 --- /dev/null +++ b/Assets/_ZoneUA/Runtime/Persistence/SaveSlotStore.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 09e3f6df128b4498a87dd99944a27119 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: From 2b0da2005ac0300e7e887df1bde858b3a4295a5b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=9D=D0=B0=D0=B7=D0=B0=D1=80?= Date: Mon, 27 Jul 2026 21:18:55 +0300 Subject: [PATCH 10/19] feat: add save game coordinator --- Assets/Script/SaveGameCoordinator.cs | 170 +++++++++++++++++++++++++++ 1 file changed, 170 insertions(+) create mode 100644 Assets/Script/SaveGameCoordinator.cs diff --git a/Assets/Script/SaveGameCoordinator.cs b/Assets/Script/SaveGameCoordinator.cs new file mode 100644 index 0000000..394d66c --- /dev/null +++ b/Assets/Script/SaveGameCoordinator.cs @@ -0,0 +1,170 @@ +using System; +using System.IO; +using UnityEngine; +using UnityEngine.SceneManagement; +using ZoneUA.Persistence; + +[DisallowMultipleComponent] +public sealed class SaveGameCoordinator : MonoBehaviour +{ + [SerializeField] private Transform playerRoot; + [SerializeField] private Health playerHealth; + [SerializeField] private WeaponSwitcher weaponSwitcher; + [SerializeField] private SceneBootstrapper sceneBootstrapper; + [SerializeField] private string defaultSlot = "autosave"; + [SerializeField, Min(0f)] private float autosaveIntervalSeconds = 120f; + [SerializeField] private bool autosaveOnApplicationPause = true; + [SerializeField] private bool autosaveOnApplicationQuit = true; + + private SaveSlotStore store; + private SaveGameData pendingRestore; + private float autosaveTimer; + + public event Action Saved; + public event Action Loaded; + public event Action SaveFailed; + public event Action LoadFailed; + + private void Awake() + { + store = new SaveSlotStore(Path.Combine(Application.persistentDataPath, "Saves")); + ResolveReferences(); + } + + private void OnEnable() + { + if (sceneBootstrapper != null) sceneBootstrapper.SceneActivated += OnSceneActivated; + } + + private void OnDisable() + { + if (sceneBootstrapper != null) sceneBootstrapper.SceneActivated -= OnSceneActivated; + } + + private void Update() + { + if (autosaveIntervalSeconds <= 0f) return; + autosaveTimer += Time.unscaledDeltaTime; + if (autosaveTimer < autosaveIntervalSeconds) return; + autosaveTimer = 0f; + Save(defaultSlot); + } + + [ContextMenu("Save Default Slot")] + public void SaveDefault() => Save(defaultSlot); + + [ContextMenu("Load Default Slot")] + public void LoadDefault() => Load(defaultSlot); + + public bool Save(string slotId) + { + try + { + ResolveReferences(); + SaveGameData data = Capture(slotId); + store.Save(slotId, data); + Saved?.Invoke(slotId); + return true; + } + catch (Exception exception) + { + Debug.LogException(exception, this); + SaveFailed?.Invoke(exception.Message); + return false; + } + } + + public bool Load(string slotId) + { + if (!store.TryLoad(slotId, out SaveGameData data)) + { + LoadFailed?.Invoke($"Save slot '{slotId}' is missing or invalid."); + return false; + } + + pendingRestore = data; + string currentScene = SceneManager.GetActiveScene().name; + if (sceneBootstrapper != null && !string.IsNullOrWhiteSpace(data.activeScene) && data.activeScene != currentScene) + { + sceneBootstrapper.LoadScene(data.activeScene); + return true; + } + + ApplyPendingRestore(slotId); + return true; + } + + public bool Delete(string slotId) + { + store.Delete(slotId); + return !store.Exists(slotId); + } + + private SaveGameData Capture(string slotId) + { + var data = new SaveGameData + { + activeScene = SceneManager.GetActiveScene().name, + player = new PlayerSaveData() + }; + data.Stamp(slotId, DateTime.UtcNow); + + if (playerRoot != null) + { + data.player.position = playerRoot.position; + data.player.rotationZ = playerRoot.eulerAngles.z; + } + if (playerHealth != null) + { + data.player.currentHealth = playerHealth.CurrentHealth; + data.player.maximumHealth = playerHealth.MaximumHealth; + } + if (weaponSwitcher != null) data.player.activeWeaponIndex = weaponSwitcher.ActiveWeaponIndex; + return data; + } + + private void ApplyPendingRestore(string slotId) + { + if (pendingRestore == null) return; + ResolveReferences(); + PlayerSaveData player = pendingRestore.player ?? new PlayerSaveData(); + if (playerRoot != null) + { + playerRoot.SetPositionAndRotation(player.position, Quaternion.Euler(0f, 0f, player.rotationZ)); + } + if (playerHealth != null) + { + playerHealth.SetMaximumHealth(player.maximumHealth); + playerHealth.SetHealth(player.currentHealth); + } + if (weaponSwitcher != null && player.activeWeaponIndex >= 0) + { + weaponSwitcher.RequestSwitch(player.activeWeaponIndex); + } + pendingRestore = null; + Loaded?.Invoke(slotId); + } + + private void OnSceneActivated(string sceneName) => ApplyPendingRestore(defaultSlot); + + private void ResolveReferences() + { + playerRoot ??= playerHealth != null ? playerHealth.transform : null; + if (playerRoot != null) + { + playerHealth ??= playerRoot.GetComponent(); + weaponSwitcher ??= playerRoot.GetComponent(); + } + sceneBootstrapper ??= SceneBootstrapper.Instance; + } + + private void OnApplicationPause(bool paused) + { + if (paused && autosaveOnApplicationPause) Save(defaultSlot); + } + + private void OnApplicationQuit() + { + if (autosaveOnApplicationQuit) Save(defaultSlot); + } +} From 50e25b8229006f061c6c34d666c4f1fa6750fffe Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=9D=D0=B0=D0=B7=D0=B0=D1=80?= Date: Mon, 27 Jul 2026 21:19:54 +0300 Subject: [PATCH 11/19] feat: expose active weapon slot for persistence --- Assets/Script/WeaponSwitcher.cs | 74 ++++++--------------------------- 1 file changed, 13 insertions(+), 61 deletions(-) diff --git a/Assets/Script/WeaponSwitcher.cs b/Assets/Script/WeaponSwitcher.cs index 4edb2bd..dedee92 100644 --- a/Assets/Script/WeaponSwitcher.cs +++ b/Assets/Script/WeaponSwitcher.cs @@ -26,6 +26,7 @@ public sealed class WeaponSwitcher : MonoBehaviour public GameObject SelectedWeapon => selectedWeapon; public WeaponController ActiveWeaponController { get; private set; } public bool IsSwitching => isSwitching; + public int ActiveWeaponIndex => Array.IndexOf(weapons, selectedWeapon); private void Awake() { @@ -34,11 +35,7 @@ private void Awake() for (int i = 0; i < weapons.Length; i++) { - if (weapons[i] == null) - { - continue; - } - + if (weapons[i] == null) continue; animators[i] = weapons[i].GetComponent(); controllers[i] = weapons[i].GetComponent(); } @@ -54,42 +51,22 @@ private void Start() return; } } - SetActiveWeapon(null, null); } public void RequestSwitch(int index) { - if (isSwitching || index < 0 || index >= weapons.Length || weapons[index] == null) - { - return; - } - - if (selectedWeapon == weapons[index]) - { - return; - } - - if (switchRoutine != null) - { - StopCoroutine(switchRoutine); - } - - switchRoutine = StartCoroutine(SwitchWeaponRoutine( - weapons[index], - animators[index], - controllers[index])); + if (isSwitching || index < 0 || index >= weapons.Length || weapons[index] == null) return; + if (selectedWeapon == weapons[index]) return; + if (switchRoutine != null) StopCoroutine(switchRoutine); + switchRoutine = StartCoroutine(SwitchWeaponRoutine(weapons[index], animators[index], controllers[index])); } - private IEnumerator SwitchWeaponRoutine( - GameObject newWeapon, - Animator newAnimator, - WeaponController newController) + private IEnumerator SwitchWeaponRoutine(GameObject newWeapon, Animator newAnimator, WeaponController newController) { isSwitching = true; ActiveWeaponController?.StopFire(); SetAllWeaponsActive(false); - newWeapon.SetActive(true); SetActiveWeapon(newWeapon, newController); @@ -99,18 +76,9 @@ private IEnumerator SwitchWeaponRoutine( newAnimator.SetTrigger(SwitchHash); } - if (switchingTime > 0f) - { - yield return new WaitForSeconds(switchingTime); - } - + if (switchingTime > 0f) yield return new WaitForSeconds(switchingTime); newController?.WeaponChanged(); - - if (newAnimator != null) - { - newAnimator.enabled = false; - } - + if (newAnimator != null) newAnimator.enabled = false; isSwitching = false; switchRoutine = null; } @@ -122,7 +90,6 @@ public void HideAllWeapons() StopCoroutine(switchRoutine); switchRoutine = null; } - ActiveWeaponController?.StopFire(); isSwitching = false; SetAllWeaponsActive(false); @@ -131,11 +98,7 @@ public void HideAllWeapons() private void SetActiveWeapon(GameObject weaponObject, WeaponController controller) { - if (selectedWeapon == weaponObject && ActiveWeaponController == controller) - { - return; - } - + if (selectedWeapon == weaponObject && ActiveWeaponController == controller) return; selectedWeapon = weaponObject; ActiveWeaponController = controller; ActiveWeaponChanged?.Invoke(controller); @@ -144,21 +107,10 @@ private void SetActiveWeapon(GameObject weaponObject, WeaponController controlle private void SetAllWeaponsActive(bool state) { for (int i = 0; i < weapons.Length; i++) - { - if (weapons[i] != null) - { - weapons[i].SetActive(state); - } - } + if (weapons[i] != null) weapons[i].SetActive(state); } - private void OnDisable() - { - ActiveWeaponController?.StopFire(); - } + private void OnDisable() => ActiveWeaponController?.StopFire(); - private void OnValidate() - { - switchingTime = Mathf.Max(0f, switchingTime); - } + private void OnValidate() => switchingTime = Mathf.Max(0f, switchingTime); } From 044c120840ed51b3591320c96de181f59e5b23c3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=9D=D0=B0=D0=B7=D0=B0=D1=80?= Date: Mon, 27 Jul 2026 21:20:28 +0300 Subject: [PATCH 12/19] fix: keep checksum implementation Unity compatible --- Assets/_ZoneUA/Runtime/Persistence/SaveSlotStore.cs | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/Assets/_ZoneUA/Runtime/Persistence/SaveSlotStore.cs b/Assets/_ZoneUA/Runtime/Persistence/SaveSlotStore.cs index 6170616..bfb7814 100644 --- a/Assets/_ZoneUA/Runtime/Persistence/SaveSlotStore.cs +++ b/Assets/_ZoneUA/Runtime/Persistence/SaveSlotStore.cs @@ -31,7 +31,6 @@ public void Save(string slotId, SaveGameData data) { if (data == null) throw new ArgumentNullException(nameof(data)); Directory.CreateDirectory(rootDirectory); - string payload = JsonUtility.ToJson(data, false); var envelope = new SaveEnvelope { payload = payload, checksum = ComputeChecksum(payload) }; string serialized = JsonUtility.ToJson(envelope, true); @@ -81,9 +80,11 @@ private static bool TryLoadPath(string path, out SaveGameData data) private static string ComputeChecksum(string value) { - using SHA256 sha = SHA256.Create(); - byte[] bytes = sha.ComputeHash(Encoding.UTF8.GetBytes(value ?? string.Empty)); - return Convert.ToHexString(bytes); + using (SHA256 sha = SHA256.Create()) + { + byte[] bytes = sha.ComputeHash(Encoding.UTF8.GetBytes(value ?? string.Empty)); + return BitConverter.ToString(bytes).Replace("-", string.Empty); + } } private static string Sanitize(string slotId) From 625c751ba6473a3462569102538f7d9c9d012a50 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=9D=D0=B0=D0=B7=D0=B0=D1=80?= Date: Mon, 27 Jul 2026 21:20:43 +0300 Subject: [PATCH 13/19] chore: add save coordinator meta --- Assets/Script/SaveGameCoordinator.cs.meta | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 Assets/Script/SaveGameCoordinator.cs.meta diff --git a/Assets/Script/SaveGameCoordinator.cs.meta b/Assets/Script/SaveGameCoordinator.cs.meta new file mode 100644 index 0000000..2e059f6 --- /dev/null +++ b/Assets/Script/SaveGameCoordinator.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: e3cc48e7145944efa7f42891d44233b9 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: -1500 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: From 70d5747e240f6b34de3a35abe600322d8357add8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=9D=D0=B0=D0=B7=D0=B0=D1=80?= Date: Mon, 27 Jul 2026 21:20:56 +0300 Subject: [PATCH 14/19] test: reference persistence assembly --- .../_ZoneUA/Tests/EditMode/ZoneUA.Combat.EditModeTests.asmdef | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Assets/_ZoneUA/Tests/EditMode/ZoneUA.Combat.EditModeTests.asmdef b/Assets/_ZoneUA/Tests/EditMode/ZoneUA.Combat.EditModeTests.asmdef index 506e994..7999c47 100644 --- a/Assets/_ZoneUA/Tests/EditMode/ZoneUA.Combat.EditModeTests.asmdef +++ b/Assets/_ZoneUA/Tests/EditMode/ZoneUA.Combat.EditModeTests.asmdef @@ -10,7 +10,8 @@ "ZoneUA.World", "ZoneUA.Input", "ZoneUA.Performance", - "ZoneUA.SceneManagement" + "ZoneUA.SceneManagement", + "ZoneUA.Persistence" ], "includePlatforms": [ "Editor" From 9c674f5d72fba2affb4239f24c82261bf390af08 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=9D=D0=B0=D0=B7=D0=B0=D1=80?= Date: Mon, 27 Jul 2026 21:21:30 +0300 Subject: [PATCH 15/19] fix: preserve slot and world seed during deferred restore --- Assets/Script/SaveGameCoordinator.cs | 35 ++++++++++++++++++---------- 1 file changed, 23 insertions(+), 12 deletions(-) diff --git a/Assets/Script/SaveGameCoordinator.cs b/Assets/Script/SaveGameCoordinator.cs index 394d66c..74f5623 100644 --- a/Assets/Script/SaveGameCoordinator.cs +++ b/Assets/Script/SaveGameCoordinator.cs @@ -12,14 +12,17 @@ public sealed class SaveGameCoordinator : MonoBehaviour [SerializeField] private WeaponSwitcher weaponSwitcher; [SerializeField] private SceneBootstrapper sceneBootstrapper; [SerializeField] private string defaultSlot = "autosave"; + [SerializeField] private int currentWorldSeed; [SerializeField, Min(0f)] private float autosaveIntervalSeconds = 120f; [SerializeField] private bool autosaveOnApplicationPause = true; [SerializeField] private bool autosaveOnApplicationQuit = true; private SaveSlotStore store; private SaveGameData pendingRestore; + private string pendingSlotId = string.Empty; private float autosaveTimer; + public int CurrentWorldSeed => currentWorldSeed; public event Action Saved; public event Action Loaded; public event Action SaveFailed; @@ -50,6 +53,8 @@ private void Update() Save(defaultSlot); } + public void SetWorldSeed(int seed) => currentWorldSeed = seed; + [ContextMenu("Save Default Slot")] public void SaveDefault() => Save(defaultSlot); @@ -61,8 +66,7 @@ public bool Save(string slotId) try { ResolveReferences(); - SaveGameData data = Capture(slotId); - store.Save(slotId, data); + store.Save(slotId, Capture(slotId)); Saved?.Invoke(slotId); return true; } @@ -83,14 +87,21 @@ public bool Load(string slotId) } pendingRestore = data; + pendingSlotId = slotId; string currentScene = SceneManager.GetActiveScene().name; if (sceneBootstrapper != null && !string.IsNullOrWhiteSpace(data.activeScene) && data.activeScene != currentScene) { - sceneBootstrapper.LoadScene(data.activeScene); + if (!sceneBootstrapper.LoadScene(data.activeScene)) + { + pendingRestore = null; + pendingSlotId = string.Empty; + LoadFailed?.Invoke($"Could not start loading scene '{data.activeScene}'."); + return false; + } return true; } - ApplyPendingRestore(slotId); + ApplyPendingRestore(); return true; } @@ -105,10 +116,10 @@ private SaveGameData Capture(string slotId) var data = new SaveGameData { activeScene = SceneManager.GetActiveScene().name, + worldSeed = currentWorldSeed, player = new PlayerSaveData() }; data.Stamp(slotId, DateTime.UtcNow); - if (playerRoot != null) { data.player.position = playerRoot.position; @@ -123,29 +134,29 @@ private SaveGameData Capture(string slotId) return data; } - private void ApplyPendingRestore(string slotId) + private void ApplyPendingRestore() { if (pendingRestore == null) return; ResolveReferences(); + currentWorldSeed = pendingRestore.worldSeed; PlayerSaveData player = pendingRestore.player ?? new PlayerSaveData(); if (playerRoot != null) - { playerRoot.SetPositionAndRotation(player.position, Quaternion.Euler(0f, 0f, player.rotationZ)); - } if (playerHealth != null) { playerHealth.SetMaximumHealth(player.maximumHealth); playerHealth.SetHealth(player.currentHealth); } if (weaponSwitcher != null && player.activeWeaponIndex >= 0) - { weaponSwitcher.RequestSwitch(player.activeWeaponIndex); - } + + string loadedSlot = pendingSlotId; pendingRestore = null; - Loaded?.Invoke(slotId); + pendingSlotId = string.Empty; + Loaded?.Invoke(loadedSlot); } - private void OnSceneActivated(string sceneName) => ApplyPendingRestore(defaultSlot); + private void OnSceneActivated(string sceneName) => ApplyPendingRestore(); private void ResolveReferences() { From 77433ee918a83c5febae95beb198cabf3affa754 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=9D=D0=B0=D0=B7=D0=B0=D1=80?= Date: Mon, 27 Jul 2026 21:21:50 +0300 Subject: [PATCH 16/19] test: cover save migration and atomic storage --- .../EditMode/SaveGamePersistenceTests.cs | 109 ++++++++++++++++++ 1 file changed, 109 insertions(+) create mode 100644 Assets/_ZoneUA/Tests/EditMode/SaveGamePersistenceTests.cs diff --git a/Assets/_ZoneUA/Tests/EditMode/SaveGamePersistenceTests.cs b/Assets/_ZoneUA/Tests/EditMode/SaveGamePersistenceTests.cs new file mode 100644 index 0000000..9190417 --- /dev/null +++ b/Assets/_ZoneUA/Tests/EditMode/SaveGamePersistenceTests.cs @@ -0,0 +1,109 @@ +using System; +using System.IO; +using NUnit.Framework; +using UnityEngine; +using ZoneUA.Persistence; + +namespace ZoneUA.Combat.Tests +{ + public sealed class SaveGamePersistenceTests + { + private string tempDirectory; + + [SetUp] + public void SetUp() + { + tempDirectory = Path.Combine(Path.GetTempPath(), "ZoneUA_SaveTests_" + Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(tempDirectory); + } + + [TearDown] + public void TearDown() + { + if (Directory.Exists(tempDirectory)) Directory.Delete(tempDirectory, true); + } + + [Test] + public void Migrate_VersionOne_UpgradesAndClampsHealth() + { + var data = new SaveGameData + { + schemaVersion = 1, + player = new PlayerSaveData { currentHealth = 150, maximumHealth = 0 } + }; + + SaveGameData migrated = SaveGameMigrator.Migrate(data); + + Assert.That(migrated.schemaVersion, Is.EqualTo(SaveGameData.CurrentSchemaVersion)); + Assert.That(migrated.player.maximumHealth, Is.EqualTo(150)); + Assert.That(migrated.player.currentHealth, Is.EqualTo(150)); + } + + [Test] + public void Migrate_FutureVersion_Throws() + { + var data = new SaveGameData { schemaVersion = SaveGameData.CurrentSchemaVersion + 1 }; + Assert.Throws(() => SaveGameMigrator.Migrate(data)); + } + + [Test] + public void Store_SaveAndLoad_RoundTripsSnapshot() + { + var store = new SaveSlotStore(tempDirectory); + var data = new SaveGameData + { + activeScene = "Production", + worldSeed = 42, + player = new PlayerSaveData + { + position = new Vector3(3f, 4f, 0f), + currentHealth = 73, + maximumHealth = 100, + activeWeaponIndex = 1 + } + }; + data.Stamp("slot-a", DateTime.UtcNow); + + store.Save("slot-a", data); + bool loaded = store.TryLoad("slot-a", out SaveGameData restored); + + Assert.That(loaded, Is.True); + Assert.That(restored.activeScene, Is.EqualTo("Production")); + Assert.That(restored.worldSeed, Is.EqualTo(42)); + Assert.That(restored.player.position, Is.EqualTo(new Vector3(3f, 4f, 0f))); + Assert.That(restored.player.currentHealth, Is.EqualTo(73)); + Assert.That(restored.player.activeWeaponIndex, Is.EqualTo(1)); + } + + [Test] + public void Store_CorruptedPrimary_FallsBackToBackup() + { + var store = new SaveSlotStore(tempDirectory); + var first = new SaveGameData { worldSeed = 10 }; + first.Stamp("slot", DateTime.UtcNow); + store.Save("slot", first); + + var second = new SaveGameData { worldSeed = 20 }; + second.Stamp("slot", DateTime.UtcNow); + store.Save("slot", second); + File.WriteAllText(store.GetSlotPath("slot"), "corrupted"); + + Assert.That(store.TryLoad("slot", out SaveGameData restored), Is.True); + Assert.That(restored.worldSeed, Is.EqualTo(10)); + } + + [Test] + public void Store_Delete_RemovesPrimaryAndBackup() + { + var store = new SaveSlotStore(tempDirectory); + var data = new SaveGameData(); + data.Stamp("slot", DateTime.UtcNow); + store.Save("slot", data); + store.Save("slot", data); + + store.Delete("slot"); + + Assert.That(store.Exists("slot"), Is.False); + } + } +} From b3dd9751ef4b8796cdfdd37275ec3b631f8d96dd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=9D=D0=B0=D0=B7=D0=B0=D1=80?= Date: Mon, 27 Jul 2026 21:22:02 +0300 Subject: [PATCH 17/19] chore: add persistence tests meta --- .../Tests/EditMode/SaveGamePersistenceTests.cs.meta | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 Assets/_ZoneUA/Tests/EditMode/SaveGamePersistenceTests.cs.meta diff --git a/Assets/_ZoneUA/Tests/EditMode/SaveGamePersistenceTests.cs.meta b/Assets/_ZoneUA/Tests/EditMode/SaveGamePersistenceTests.cs.meta new file mode 100644 index 0000000..6c64365 --- /dev/null +++ b/Assets/_ZoneUA/Tests/EditMode/SaveGamePersistenceTests.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 1f8350897cc245349464714ef75e64e2 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: From e1021cd7e9b7b589144696d93af2e8095640a83c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=9D=D0=B0=D0=B7=D0=B0=D1=80?= Date: Mon, 27 Jul 2026 21:22:27 +0300 Subject: [PATCH 18/19] docs: add save load integration guide --- Docs/SAVE_LOAD_PERSISTENT_STATE.md | 103 +++++++++++++++++++++++++++++ 1 file changed, 103 insertions(+) create mode 100644 Docs/SAVE_LOAD_PERSISTENT_STATE.md diff --git a/Docs/SAVE_LOAD_PERSISTENT_STATE.md b/Docs/SAVE_LOAD_PERSISTENT_STATE.md new file mode 100644 index 0000000..c19b067 --- /dev/null +++ b/Docs/SAVE_LOAD_PERSISTENT_STATE.md @@ -0,0 +1,103 @@ +# Save/load and persistent state + +This module introduces a versioned save format and a single runtime coordinator for player-facing persistence. + +## Stored state + +`SaveGameData` currently stores: + +- schema version; +- save identifier and UTC timestamp; +- active gameplay scene; +- world seed; +- player position and Z rotation; +- current and maximum health; +- active weapon slot. + +The schema is intentionally explicit. New persistent fields must be added with a schema-version increment and a migration step. + +## Storage guarantees + +`SaveSlotStore` writes under: + +`Application.persistentDataPath/Saves` + +Each slot uses: + +- `.json` for the primary save; +- `.json.bak` for the previous valid save; +- `.json.tmp` during atomic replacement. + +The payload is wrapped in an envelope with a SHA-256 checksum. Loading tries the primary file first and falls back to the backup if the primary file is missing, truncated, malformed or fails checksum validation. + +## Bootstrap setup + +Add `SaveGameCoordinator` to the persistent Bootstrap root beside: + +- `GlobalSystem`; +- `SceneBootstrapper`. + +Assign: + +- player root; +- player `Health`; +- player `WeaponSwitcher`; +- `SceneBootstrapper`; +- default slot; +- autosave interval. + +The coordinator can resolve player references from the configured player root. For production, explicit Inspector references are preferred. + +## Scene transitions + +When a save references another gameplay scene, the coordinator asks `SceneBootstrapper` to load it. Player position, health and weapon slot are restored only after `SceneActivated` fires. + +Overlapping scene transitions are rejected by the existing scene state machine. A failed transition produces `LoadFailed` and does not apply a partial snapshot. + +## World seed integration + +The world generator should call: + +`SaveGameCoordinator.SetWorldSeed(resolvedSeed)` + +immediately after resolving or generating the seed. During load, read `CurrentWorldSeed` before regenerating the world. The world must finish deterministic generation before player-dependent simulation resumes. + +## Public API + +- `SaveDefault()` +- `LoadDefault()` +- `Save(slotId)` +- `Load(slotId)` +- `Delete(slotId)` +- `SetWorldSeed(seed)` + +Events: + +- `Saved` +- `Loaded` +- `SaveFailed` +- `LoadFailed` + +## Migration policy + +`SaveGameMigrator` upgrades old snapshots one version at a time. Saves from a newer unsupported schema are rejected rather than loaded partially. + +Never silently reinterpret a field. For renamed or structurally changed data, add an explicit migration and a test fixture representing the old schema. + +## Required Unity validation + +1. Open the project in Unity 6000.5.5f1. +2. Run all `SaveGamePersistenceTests`. +3. Add `SaveGameCoordinator` to Bootstrap. +4. Wire the production player references. +5. Save in Production, move and take damage, then load. +6. Save with weapon slot 2 active and verify restoration. +7. Save in another gameplay scene and verify additive transition before restore. +8. Corrupt the primary save and verify backup recovery. +9. Pause/resume on Android and verify pause autosave. +10. Verify quitting does not throw during Unity shutdown. +11. Verify the deterministic world seed is applied before player simulation. + +## Not yet persisted + +The current schema does not claim to persist every runtime object. NPC state, dropped items, constructed buildings, inventories and mutable world objects should be added through a separate stable-ID participant layer after their runtime ownership rules are finalised. From cf82e67898ba7c35b5caa390d9e529051085f54d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=9D=D0=B0=D0=B7=D0=B0=D1=80?= Date: Mon, 27 Jul 2026 21:22:46 +0300 Subject: [PATCH 19/19] chore: add save load guide meta --- Docs/SAVE_LOAD_PERSISTENT_STATE.md.meta | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 Docs/SAVE_LOAD_PERSISTENT_STATE.md.meta diff --git a/Docs/SAVE_LOAD_PERSISTENT_STATE.md.meta b/Docs/SAVE_LOAD_PERSISTENT_STATE.md.meta new file mode 100644 index 0000000..116bb38 --- /dev/null +++ b/Docs/SAVE_LOAD_PERSISTENT_STATE.md.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 18818f55b7304db395c9d23f2a8c516d +TextScriptImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: