using UnityEngine; namespace Interactions { /// /// Base class for interactables that participate in the save/load system. /// Provides common save ID generation and serialization infrastructure. /// public abstract class SaveableInteractable : InteractableBase { [Header("Save System")] [SerializeField] // Save system configuration public override bool AutoRegisterForSave => true; /// /// Flag to indicate we're currently restoring from save data. /// Child classes can check this to skip initialization logic during load. /// protected bool IsRestoringFromSave { get; private set; } #region Save/Load Lifecycle Hooks protected override string OnSceneSaveRequested() { object stateData = GetSerializableState(); if (stateData == null) { return "{}"; } return JsonUtility.ToJson(stateData); } protected override void OnSceneRestoreRequested(string serializedData) { if (string.IsNullOrEmpty(serializedData)) { Debug.LogWarning($"[SaveableInteractable] Empty save data for {SaveId}"); return; } // OnSceneRestoreRequested is guaranteed by the lifecycle system to only fire during actual restoration // No need to check IsRestoringState - the lifecycle manager handles timing deterministically IsRestoringFromSave = true; try { ApplySerializableState(serializedData); } catch (System.Exception e) { Debug.LogError($"[SaveableInteractable] Failed to restore state for {SaveId}: {e.Message}"); } finally { IsRestoringFromSave = false; } } #endregion #region Virtual Methods for Child Classes /// /// Child classes override this to return their serializable state data. /// Return an object that can be serialized with JsonUtility. /// protected abstract object GetSerializableState(); /// /// Child classes override this to apply restored state data. /// Should NOT trigger events or re-initialize logic that already happened. /// /// JSON string containing the saved state protected abstract void ApplySerializableState(string serializedData); #endregion #region Editor Helpers #if UNITY_EDITOR [ContextMenu("Log Save ID")] private void LogSaveId() { Debug.Log($"Save ID: {SaveId}"); } [ContextMenu("Test Serialize/Deserialize")] private void TestSerializeDeserialize() { string serialized = OnSceneSaveRequested(); Debug.Log($"Serialized state: {serialized}"); OnSceneRestoreRequested(serialized); Debug.Log("Deserialization test complete"); } #endif #endregion } #region Common Save Data Structures /// /// Base save data for all interactables. /// Can be extended by child classes. /// [System.Serializable] public class InteractableBaseSaveData { public bool isActive; public Vector3 worldPosition; public Quaternion worldRotation; } #endregion }