Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
181 changes: 181 additions & 0 deletions Assets/Script/SaveGameCoordinator.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,181 @@
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] 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<string> Saved;
public event Action<string> Loaded;
public event Action<string> SaveFailed;
public event Action<string> 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);
}

public void SetWorldSeed(int seed) => currentWorldSeed = seed;

[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();
store.Save(slotId, Capture(slotId));
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;
pendingSlotId = slotId;
string currentScene = SceneManager.GetActiveScene().name;
if (sceneBootstrapper != null && !string.IsNullOrWhiteSpace(data.activeScene) && data.activeScene != currentScene)
{
if (!sceneBootstrapper.LoadScene(data.activeScene))
{
pendingRestore = null;
pendingSlotId = string.Empty;
LoadFailed?.Invoke($"Could not start loading scene '{data.activeScene}'.");
return false;
}
return true;
}

ApplyPendingRestore();
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,
worldSeed = currentWorldSeed,
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()
{
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;
pendingSlotId = string.Empty;
Loaded?.Invoke(loadedSlot);
}

private void OnSceneActivated(string sceneName) => ApplyPendingRestore();

private void ResolveReferences()
{
playerRoot ??= playerHealth != null ? playerHealth.transform : null;
if (playerRoot != null)
{
playerHealth ??= playerRoot.GetComponent<Health>();
weaponSwitcher ??= playerRoot.GetComponent<WeaponSwitcher>();
}
sceneBootstrapper ??= SceneBootstrapper.Instance;
}

private void OnApplicationPause(bool paused)
{
if (paused && autosaveOnApplicationPause) Save(defaultSlot);
}

private void OnApplicationQuit()
{
if (autosaveOnApplicationQuit) Save(defaultSlot);
}
}
11 changes: 11 additions & 0 deletions Assets/Script/SaveGameCoordinator.cs.meta

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

74 changes: 13 additions & 61 deletions Assets/Script/WeaponSwitcher.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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()
{
Expand All @@ -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<Animator>();
controllers[i] = weapons[i].GetComponent<WeaponController>();
}
Expand All @@ -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);

Expand All @@ -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;
}
Expand All @@ -122,7 +90,6 @@ public void HideAllWeapons()
StopCoroutine(switchRoutine);
switchRoutine = null;
}

ActiveWeaponController?.StopFire();
isSwitching = false;
SetAllWeaponsActive(false);
Expand All @@ -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);
Expand All @@ -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);
}
8 changes: 8 additions & 0 deletions Assets/_ZoneUA/Runtime/Persistence.meta

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

36 changes: 36 additions & 0 deletions Assets/_ZoneUA/Runtime/Persistence/SaveGameData.cs
Original file line number Diff line number Diff line change
@@ -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;
}
}
11 changes: 11 additions & 0 deletions Assets/_ZoneUA/Runtime/Persistence/SaveGameData.cs.meta

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading
Loading