using System.Collections; using System.Collections.Generic; using System.Text; using UnityEngine; public class BackgroundSave : MonoBehaviour { static public BackgroundSave Instance { get; private set; } private string _localUDT = ""; private string _serverUDT = ""; #if UNITY_EDITOR [SerializeField] #endif private float _defaultSaveInterval = 5.0f * 60.0f; private float _saveInterval; private float _timer; private float _delayAmount = 5.0f; private bool _isEnabled; #if UNITY_EDITOR [SerializeField] private bool TEST_force_enabled = false; [SerializeField] private bool TEST_force_save = false; #endif private void Awake() { if (Instance != null && Instance != this) { Debug.Log($"Cannot have multiple instances of class {nameof(BackgroundSave)}."); Destroy(gameObject); return; } Instance = this; } private void Update() { #if UNITY_EDITOR && false _isEnabled = TEST_force_enabled; #endif if (!_isEnabled) { return; } #if UNITY_EDITOR if (!TEST_force_save && _timer < _saveInterval) #else if (_timer < _saveInterval) #endif { _timer += Time.deltaTime; return; } bool isReadyToSave = SceneModeManager.CompareSceneMode(SceneModes.Navigate); if (isReadyToSave) { Debug.Log("Background Save : Getting local save"); byte[] bytes = SaveXML.BuildXmlBytes(); _localUDT = Encoding.UTF8.GetString(bytes); bool isModified = _localUDT != _serverUDT; if (!isModified) { Debug.Log("Background Save : No changes detected"); ResetTimer(); return; } if (_localUDT != _serverUDT) { Debug.Log("Background Save : Saving to server"); StartCoroutine(LoadHistory.Instance.RequestAutoSaveToServer(_localUDT)); } else { Debug.Log("Background Save : No changes made (matching local and server saves)"); } ResetTimer(); } else { #if UNITY_EDITOR if (TEST_force_save) { return; } #endif Debug.Log("Background Save : Waiting To Save..."); _timer -= _delayAmount; } } public void InitTimer() { if (!_isEnabled) { Debug.Log("Background Save : Init"); _saveInterval = _defaultSaveInterval; _timer = 0.0f; _isEnabled = true; } } public void StopTimer() { Debug.Log("Background Save : Timer Stopped"); _timer = 0.0f; _isEnabled = false; } public void ResetTimer() { Debug.Log("Background Save : Timer Reset"); _timer = 0.0f; #if UNITY_EDITOR TEST_force_save = false; #endif } public void SetLastestServerUDT(string udt) { _serverUDT = udt; } public string GetLastestServerUDT() { return _serverUDT; } public void ValidateRefId() { if (!_P.AutoSave_RefId || string.IsNullOrEmpty(_G.ref_id)) { _P.AutoSave_RefId = false; Destroy(gameObject); } } }