Files
zeling_v2/Assets/Scripts/Core/Save/EmergencySaveService.cs
2026-05-12 15:34:08 +08:00

54 lines
1.7 KiB
C#

using System.Threading.Tasks;
using UnityEngine;
using BaseGames.Core.Events;
namespace BaseGames.Core.Save
{
public class EmergencySaveService : MonoBehaviour
{
public const int EmergencySlot = 99;
[SerializeField] private float _intervalSeconds = 120f;
[SerializeField] private SaveManager _saveManager;
[SerializeField] private BoolEventChannelSO _onGameplayActive;
private bool _gameplayActive;
private float _timer;
private readonly CompositeDisposable _subscriptions = new();
private void OnEnable()
{
_onGameplayActive?.Subscribe(OnGameplayActiveChanged).AddTo(_subscriptions);
}
private void OnDisable() => _subscriptions.Clear();
private void OnGameplayActiveChanged(bool value) => _gameplayActive = value;
private void Update()
{
if (!_gameplayActive || _saveManager == null) return;
_timer += Time.deltaTime;
if (_timer >= _intervalSeconds)
{
_timer = 0f;
_ = _saveManager.SaveAsync(EmergencySlot);
}
}
public bool HasEmergencySave()
=> _saveManager != null && _saveManager.SlotExists(EmergencySlot);
public async Task PromoteToSlot(int targetSlot)
{
if (_saveManager == null) return;
var storage = new LocalFileStorage();
if (!storage.Exists(EmergencySlot)) return;
string json = await storage.ReadAsync(EmergencySlot);
if (json == null) return;
await storage.WriteAsync(targetSlot, json);
await storage.DeleteAsync(EmergencySlot);
}
}
}