Refactor interactions, introduce template-method lifecycle management, work on save-load system (#51)
# Lifecycle Management & Save System Revamp
## Overview
Complete overhaul of game lifecycle management, interactable system, and save/load architecture. Introduces centralized `ManagedBehaviour` base class for consistent initialization ordering and lifecycle hooks across all systems.
## Core Architecture
### New Lifecycle System
- **`LifecycleManager`**: Centralized coordinator for all managed objects
- **`ManagedBehaviour`**: Base class replacing ad-hoc initialization patterns
- `OnManagedAwake()`: Priority-based initialization (0-100, lower = earlier)
- `OnSceneReady()`: Scene-specific setup after managers ready
- Replaces `BootCompletionService` (deleted)
- **Priority groups**: Infrastructure (0-20) → Game Systems (30-50) → Data (60-80) → UI/Gameplay (90-100)
- **Editor support**: `EditorLifecycleBootstrap` ensures lifecycle works in editor mode
### Unified SaveID System
- Consistent format: `{ParentName}_{ComponentType}`
- Auto-registration via `AutoRegisterForSave = true`
- New `DebugSaveIds` editor tool for inspection
## Save/Load Improvements
### Enhanced State Management
- **Extended SaveLoadData**: Unlocked minigames, card collection states, combination items, slot occupancy
- **Async loading**: `ApplyCardCollectionState()` waits for card definitions before restoring
- **New `SaveablePlayableDirector`**: Timeline sequences save/restore playback state
- **Fixed race conditions**: Proper initialization ordering prevents data corruption
## Interactable & Pickup System
- Migrated to `OnManagedAwake()` for consistent initialization
- Template method pattern for state restoration (`RestoreInteractionState()`)
- Fixed combination item save/load bugs (items in slots vs. follower hand)
- Dynamic spawning support for combined items on load
- **Breaking**: `Interactable.Awake()` now sealed, use `OnManagedAwake()` instead
## UI System Changes
- **AlbumViewPage** and **BoosterNotificationDot**: Migrated to `ManagedBehaviour`
- **Fixed menu persistence bug**: Menus no longer reappear after scene transitions
- **Pause Menu**: Now reacts to all scene loads (not just first scene)
- **Orientation Enforcer**: Enforces per-scene via `SceneManagementService`
- **Loading Screen**: Integrated with new lifecycle
## ⚠️ Breaking Changes
1. **`BootCompletionService` removed** → Use `ManagedBehaviour.OnManagedAwake()` with priority
2. **`Interactable.Awake()` sealed** → Override `OnManagedAwake()` instead
3. **SaveID format changed** → Now `{ParentName}_{ComponentType}` consistently
4. **MonoBehaviours needing init ordering** → Must inherit from `ManagedBehaviour`
Co-authored-by: Michal Pikulski <michal.a.pikulski@gmail.com>
Co-authored-by: Michal Pikulski <michal@foolhardyhorizons.com>
Reviewed-on: #51
This commit is contained in:
48
Assets/Scripts/Core/Lifecycle/LifecycleEnums.cs
Normal file
48
Assets/Scripts/Core/Lifecycle/LifecycleEnums.cs
Normal file
@@ -0,0 +1,48 @@
|
||||
namespace Core.Lifecycle
|
||||
{
|
||||
/// <summary>
|
||||
/// Defines the different lifecycle phases that can be broadcast by the LifecycleManager.
|
||||
/// All ManagedBehaviours participate in all lifecycle phases by default.
|
||||
/// </summary>
|
||||
public enum LifecyclePhase
|
||||
{
|
||||
/// <summary>
|
||||
/// Called once per component after bootstrap completes.
|
||||
/// Guaranteed to be called after all bootstrap resources are loaded.
|
||||
/// For late-registered components, called immediately upon registration.
|
||||
/// </summary>
|
||||
ManagedAwake,
|
||||
|
||||
/// <summary>
|
||||
/// Called before a scene is unloaded.
|
||||
/// Only called for components in the scene being unloaded.
|
||||
/// </summary>
|
||||
SceneUnloading,
|
||||
|
||||
/// <summary>
|
||||
/// Called after a scene has finished loading.
|
||||
/// Only called for components in the scene being loaded.
|
||||
/// </summary>
|
||||
SceneReady,
|
||||
|
||||
/// <summary>
|
||||
/// Called before scene unloads to save data via SaveLoadManager.
|
||||
/// Integrates with existing SaveLoadManager save system.
|
||||
/// </summary>
|
||||
SaveRequested,
|
||||
|
||||
/// <summary>
|
||||
/// Called after scene loads to restore data via SaveLoadManager.
|
||||
/// Integrates with existing SaveLoadManager restore system.
|
||||
/// </summary>
|
||||
RestoreRequested,
|
||||
|
||||
/// <summary>
|
||||
/// Called during OnDestroy before component is destroyed.
|
||||
/// Use for custom cleanup logic.
|
||||
/// Most cleanup is automatic (managed events, auto-registrations).
|
||||
/// </summary>
|
||||
ManagedDestroy
|
||||
}
|
||||
}
|
||||
|
||||
2
Assets/Scripts/Core/Lifecycle/LifecycleEnums.cs.meta
Normal file
2
Assets/Scripts/Core/Lifecycle/LifecycleEnums.cs.meta
Normal file
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 5f5f0f19f08240d4d9863b6be6a3cf03
|
||||
637
Assets/Scripts/Core/Lifecycle/LifecycleManager.cs
Normal file
637
Assets/Scripts/Core/Lifecycle/LifecycleManager.cs
Normal file
@@ -0,0 +1,637 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using UnityEngine;
|
||||
|
||||
namespace Core.Lifecycle
|
||||
{
|
||||
/// <summary>
|
||||
/// Central orchestrator for ManagedBehaviour lifecycle events.
|
||||
/// Singleton that broadcasts lifecycle events in priority-ordered manner.
|
||||
/// </summary>
|
||||
public class LifecycleManager : MonoBehaviour
|
||||
{
|
||||
#region Singleton
|
||||
|
||||
private static LifecycleManager _instance;
|
||||
|
||||
/// <summary>
|
||||
/// Singleton instance of the LifecycleManager.
|
||||
/// Created by CustomBoot.Initialise() before bootstrap begins.
|
||||
/// </summary>
|
||||
public static LifecycleManager Instance => _instance;
|
||||
|
||||
/// <summary>
|
||||
/// Create LifecycleManager instance. Called by CustomBoot.Initialise() before bootstrap begins.
|
||||
/// </summary>
|
||||
public static void CreateInstance()
|
||||
{
|
||||
if (_instance != null)
|
||||
{
|
||||
Debug.LogWarning("[LifecycleManager] Instance already exists");
|
||||
return;
|
||||
}
|
||||
|
||||
var go = new GameObject("LifecycleManager");
|
||||
_instance = go.AddComponent<LifecycleManager>();
|
||||
DontDestroyOnLoad(go);
|
||||
|
||||
Debug.Log("[LifecycleManager] Instance created");
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Lifecycle Lists
|
||||
|
||||
private List<ManagedBehaviour> managedAwakeList = new List<ManagedBehaviour>();
|
||||
private List<ManagedBehaviour> sceneUnloadingList = new List<ManagedBehaviour>();
|
||||
private List<ManagedBehaviour> sceneReadyList = new List<ManagedBehaviour>();
|
||||
private List<ManagedBehaviour> saveRequestedList = new List<ManagedBehaviour>();
|
||||
private List<ManagedBehaviour> restoreRequestedList = new List<ManagedBehaviour>();
|
||||
private List<ManagedBehaviour> destroyList = new List<ManagedBehaviour>();
|
||||
|
||||
#endregion
|
||||
|
||||
#region Tracking Dictionaries
|
||||
|
||||
private Dictionary<ManagedBehaviour, string> componentScenes = new Dictionary<ManagedBehaviour, string>();
|
||||
|
||||
#endregion
|
||||
|
||||
#region State Flags
|
||||
|
||||
private bool isBootComplete = false;
|
||||
private string currentSceneReady = "";
|
||||
|
||||
// Scene loading state tracking
|
||||
private bool isLoadingScene = false;
|
||||
private string sceneBeingLoaded = "";
|
||||
private List<ManagedBehaviour> pendingSceneComponents = new List<ManagedBehaviour>();
|
||||
|
||||
[SerializeField] private bool enableDebugLogging = true;
|
||||
|
||||
#endregion
|
||||
|
||||
#region Unity Lifecycle
|
||||
|
||||
void Awake()
|
||||
{
|
||||
// Instance should already be set by CreateInstance() called from CustomBoot
|
||||
// This Awake is backup in case LifecycleManager was manually added to a scene
|
||||
if (_instance == null)
|
||||
{
|
||||
_instance = this;
|
||||
DontDestroyOnLoad(gameObject);
|
||||
LogDebug("LifecycleManager initialized via Awake (fallback)");
|
||||
}
|
||||
else if (_instance != this)
|
||||
{
|
||||
Debug.LogWarning("[LifecycleManager] Duplicate instance detected. Destroying.");
|
||||
Destroy(gameObject);
|
||||
}
|
||||
}
|
||||
|
||||
void OnDestroy()
|
||||
{
|
||||
if (_instance == this)
|
||||
{
|
||||
_instance = null;
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Registration
|
||||
|
||||
/// <summary>
|
||||
/// Register a ManagedBehaviour with the lifecycle system.
|
||||
/// Called automatically from ManagedBehaviour.Awake().
|
||||
/// All components participate in all lifecycle hooks.
|
||||
/// </summary>
|
||||
public void Register(ManagedBehaviour component)
|
||||
{
|
||||
if (component == null)
|
||||
{
|
||||
Debug.LogWarning("[LifecycleManager] Attempted to register null component");
|
||||
return;
|
||||
}
|
||||
|
||||
var sceneName = component.gameObject.scene.name;
|
||||
|
||||
// Track which scene this component belongs to
|
||||
componentScenes[component] = sceneName;
|
||||
|
||||
// ALWAYS add to managedAwakeList - this is the master list used for save/load
|
||||
InsertSorted(managedAwakeList, component, component.ManagedAwakePriority);
|
||||
|
||||
// Handle ManagedAwake timing based on boot state
|
||||
if (isBootComplete)
|
||||
{
|
||||
// Check if we're currently loading a scene
|
||||
if (isLoadingScene && sceneName == sceneBeingLoaded)
|
||||
{
|
||||
// Batch this component - will be processed in priority order when scene load completes
|
||||
pendingSceneComponents.Add(component);
|
||||
LogDebug($"Batched component for scene load: {component.gameObject.name} (Scene: {sceneName})");
|
||||
}
|
||||
else
|
||||
{
|
||||
// Truly late registration (component enabled after scene is ready)
|
||||
// Call OnManagedAwake immediately since boot already completed
|
||||
LogDebug($"Late registration: Calling OnManagedAwake immediately for {component.gameObject.name}");
|
||||
try
|
||||
{
|
||||
component.InvokeManagedAwake();
|
||||
HandleAutoRegistrations(component);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Debug.LogError($"[LifecycleManager] Error in OnManagedAwake for {component.gameObject.name}: {ex}");
|
||||
}
|
||||
}
|
||||
}
|
||||
// If boot not complete, component stays in list and will be processed by BroadcastManagedAwake()
|
||||
|
||||
// Register for all scene lifecycle hooks
|
||||
InsertSorted(sceneUnloadingList, component, component.SceneUnloadingPriority);
|
||||
InsertSorted(sceneReadyList, component, component.SceneReadyPriority);
|
||||
InsertSorted(saveRequestedList, component, component.SavePriority);
|
||||
InsertSorted(restoreRequestedList, component, component.RestorePriority);
|
||||
InsertSorted(destroyList, component, component.DestroyPriority);
|
||||
|
||||
// If this scene is already ready (and we're not in loading mode), call OnSceneReady immediately
|
||||
if (!isLoadingScene && currentSceneReady == sceneName)
|
||||
{
|
||||
LogDebug($"Late registration: Calling OnSceneReady immediately for {component.gameObject.name}");
|
||||
try
|
||||
{
|
||||
component.InvokeSceneReady();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Debug.LogError($"[LifecycleManager] Error in OnSceneReady for {component.gameObject.name}: {ex}");
|
||||
}
|
||||
}
|
||||
|
||||
LogDebug($"Registered {component.gameObject.name} (Scene: {sceneName})");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Unregister a ManagedBehaviour from the lifecycle system.
|
||||
/// Called automatically from ManagedBehaviour.OnDestroy().
|
||||
/// </summary>
|
||||
public void Unregister(ManagedBehaviour component)
|
||||
{
|
||||
if (component == null)
|
||||
return;
|
||||
|
||||
managedAwakeList.Remove(component);
|
||||
sceneUnloadingList.Remove(component);
|
||||
sceneReadyList.Remove(component);
|
||||
saveRequestedList.Remove(component);
|
||||
restoreRequestedList.Remove(component);
|
||||
destroyList.Remove(component);
|
||||
|
||||
componentScenes.Remove(component);
|
||||
|
||||
LogDebug($"Unregistered {component.gameObject.name}");
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Broadcast Methods
|
||||
|
||||
/// <summary>
|
||||
/// Called by CustomBoot when boot completes.
|
||||
/// Broadcasts ManagedAwake to all registered components.
|
||||
/// </summary>
|
||||
public void OnBootCompletionTriggered()
|
||||
{
|
||||
if (isBootComplete)
|
||||
return;
|
||||
|
||||
LogDebug("=== Boot Completion Triggered ===");
|
||||
BroadcastManagedAwake();
|
||||
isBootComplete = true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Broadcast OnManagedAwake to all registered components (priority ordered).
|
||||
/// </summary>
|
||||
private void BroadcastManagedAwake()
|
||||
{
|
||||
LogDebug($"Broadcasting ManagedAwake to {managedAwakeList.Count} components");
|
||||
|
||||
// Create a copy to avoid collection modification during iteration
|
||||
var componentsCopy = new List<ManagedBehaviour>(managedAwakeList);
|
||||
|
||||
foreach (var component in componentsCopy)
|
||||
{
|
||||
if (component == null) continue;
|
||||
|
||||
try
|
||||
{
|
||||
component.InvokeManagedAwake();
|
||||
HandleAutoRegistrations(component);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Debug.LogError($"[LifecycleManager] Error in OnManagedAwake for {component.gameObject.name}: {ex}");
|
||||
}
|
||||
}
|
||||
|
||||
// NOTE: We do NOT clear managedAwakeList here!
|
||||
// This list is reused for save/load broadcasts and must persist for the lifetime of the game.
|
||||
// Components are added during registration and removed during Unregister (OnDestroy).
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Begins scene loading mode for the specified scene.
|
||||
/// Components that register during this time will be batched and processed in priority order.
|
||||
/// Call this BEFORE starting to load a scene.
|
||||
/// </summary>
|
||||
public void BeginSceneLoad(string sceneName)
|
||||
{
|
||||
isLoadingScene = true;
|
||||
sceneBeingLoaded = sceneName;
|
||||
pendingSceneComponents.Clear();
|
||||
LogDebug($"Began scene loading mode for: {sceneName}");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Processes all batched components from the scene load in priority order.
|
||||
/// Called automatically by BroadcastSceneReady.
|
||||
/// </summary>
|
||||
private void ProcessBatchedSceneComponents()
|
||||
{
|
||||
if (pendingSceneComponents.Count == 0)
|
||||
{
|
||||
isLoadingScene = false;
|
||||
sceneBeingLoaded = "";
|
||||
return;
|
||||
}
|
||||
|
||||
LogDebug($"Processing {pendingSceneComponents.Count} batched components for scene: {sceneBeingLoaded}");
|
||||
|
||||
// Sort by ManagedAwake priority (lower values first)
|
||||
pendingSceneComponents.Sort((a, b) => a.ManagedAwakePriority.CompareTo(b.ManagedAwakePriority));
|
||||
|
||||
// Call OnManagedAwake in priority order
|
||||
foreach (var component in pendingSceneComponents)
|
||||
{
|
||||
if (component == null) continue;
|
||||
|
||||
try
|
||||
{
|
||||
component.InvokeManagedAwake();
|
||||
HandleAutoRegistrations(component);
|
||||
LogDebug($"Processed batched component: {component.gameObject.name} (Priority: {component.ManagedAwakePriority})");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Debug.LogError($"[LifecycleManager] Error in OnManagedAwake for batched component {component.gameObject.name}: {ex}");
|
||||
}
|
||||
}
|
||||
|
||||
// Clear state
|
||||
pendingSceneComponents.Clear();
|
||||
isLoadingScene = false;
|
||||
sceneBeingLoaded = "";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Broadcast OnSceneUnloading to components in the specified scene (reverse priority order).
|
||||
/// </summary>
|
||||
public void BroadcastSceneUnloading(string sceneName)
|
||||
{
|
||||
LogDebug($"Broadcasting SceneUnloading for scene: {sceneName}");
|
||||
|
||||
// Iterate backwards (high priority → low priority)
|
||||
for (int i = sceneUnloadingList.Count - 1; i >= 0; i--)
|
||||
{
|
||||
var component = sceneUnloadingList[i];
|
||||
if (component == null) continue;
|
||||
|
||||
if (componentScenes.TryGetValue(component, out string compScene) && compScene == sceneName)
|
||||
{
|
||||
try
|
||||
{
|
||||
component.InvokeSceneUnloading();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Debug.LogError($"[LifecycleManager] Error in OnSceneUnloading for {component.gameObject.name}: {ex}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Broadcast OnSceneReady to components in the specified scene (priority order).
|
||||
/// If scene loading mode is active, processes batched components first.
|
||||
/// </summary>
|
||||
public void BroadcastSceneReady(string sceneName)
|
||||
{
|
||||
LogDebug($"Broadcasting SceneReady for scene: {sceneName}");
|
||||
currentSceneReady = sceneName;
|
||||
|
||||
// If we were in scene loading mode for this scene, process batched components first
|
||||
if (isLoadingScene && sceneBeingLoaded == sceneName)
|
||||
{
|
||||
ProcessBatchedSceneComponents();
|
||||
}
|
||||
|
||||
// Create a copy to avoid collection modification during iteration
|
||||
var componentsCopy = new List<ManagedBehaviour>(sceneReadyList);
|
||||
|
||||
foreach (var component in componentsCopy)
|
||||
{
|
||||
if (component == null) continue;
|
||||
|
||||
if (componentScenes.TryGetValue(component, out string compScene) && compScene == sceneName)
|
||||
{
|
||||
try
|
||||
{
|
||||
component.InvokeSceneReady();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Debug.LogError($"[LifecycleManager] Error in OnSceneReady for {component.gameObject.name}: {ex}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Broadcasts scene save request to all registered components that opt-in.
|
||||
/// Collects and returns serialized data from components that return non-null values.
|
||||
/// Called by SaveLoadManager during scene transitions.
|
||||
/// </summary>
|
||||
public Dictionary<string, string> BroadcastSceneSaveRequested()
|
||||
{
|
||||
var saveData = new Dictionary<string, string>();
|
||||
|
||||
// Create a copy to avoid collection modification during iteration
|
||||
var componentsCopy = new List<ManagedBehaviour>(managedAwakeList);
|
||||
|
||||
foreach (var component in componentsCopy)
|
||||
{
|
||||
if (component == null || !component.AutoRegisterForSave) continue;
|
||||
|
||||
try
|
||||
{
|
||||
string serializedData = component.InvokeSceneSaveRequested();
|
||||
if (!string.IsNullOrEmpty(serializedData))
|
||||
{
|
||||
string saveId = component.SaveId;
|
||||
saveData[saveId] = serializedData;
|
||||
LogDebug($"Collected scene save data from: {saveId} (Type: {component.GetType().Name})");
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Debug.LogError($"[LifecycleManager] Exception during scene save for {component.SaveId}: {ex}");
|
||||
}
|
||||
}
|
||||
|
||||
LogDebug($"Collected scene save data from {saveData.Count} components");
|
||||
return saveData;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Broadcasts global save request to all registered components that opt-in.
|
||||
/// Collects and returns serialized data from components that return non-null values.
|
||||
/// Called by SaveLoadManager when writing save file to disk (quit, manual save).
|
||||
/// </summary>
|
||||
public Dictionary<string, string> BroadcastGlobalSaveRequested()
|
||||
{
|
||||
var saveData = new Dictionary<string, string>();
|
||||
|
||||
// Create a copy to avoid collection modification during iteration
|
||||
var componentsCopy = new List<ManagedBehaviour>(managedAwakeList);
|
||||
|
||||
foreach (var component in componentsCopy)
|
||||
{
|
||||
if (component == null || !component.AutoRegisterForSave) continue;
|
||||
|
||||
try
|
||||
{
|
||||
string serializedData = component.InvokeGlobalSaveRequested();
|
||||
if (!string.IsNullOrEmpty(serializedData))
|
||||
{
|
||||
saveData[component.SaveId] = serializedData;
|
||||
LogDebug($"Collected global save data from: {component.SaveId}");
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Debug.LogError($"[LifecycleManager] Exception during global save for {component.SaveId}: {ex}");
|
||||
}
|
||||
}
|
||||
|
||||
LogDebug($"Collected global save data from {saveData.Count} components");
|
||||
return saveData;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Broadcasts scene restore request to all registered components that opt-in.
|
||||
/// Distributes serialized data to matching components by SaveId.
|
||||
/// Called by SaveLoadManager during scene load.
|
||||
/// </summary>
|
||||
public void BroadcastSceneRestoreRequested(Dictionary<string, string> saveData)
|
||||
{
|
||||
if (saveData == null) return;
|
||||
|
||||
int restoredCount = 0;
|
||||
|
||||
// Create a copy to avoid collection modification during iteration
|
||||
// (components might destroy themselves during restoration)
|
||||
var componentsCopy = new List<ManagedBehaviour>(managedAwakeList);
|
||||
|
||||
foreach (var component in componentsCopy)
|
||||
{
|
||||
if (component == null || !component.AutoRegisterForSave) continue;
|
||||
|
||||
if (saveData.TryGetValue(component.SaveId, out string serializedData))
|
||||
{
|
||||
try
|
||||
{
|
||||
component.InvokeSceneRestoreRequested(serializedData);
|
||||
restoredCount++;
|
||||
LogDebug($"Restored scene data to: {component.SaveId}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Debug.LogError($"[LifecycleManager] Exception during scene restore for {component.SaveId}: {ex}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
LogDebug($"Restored scene data to {restoredCount} components");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Broadcasts global restore request to all registered components that opt-in.
|
||||
/// Distributes serialized data to matching components by SaveId.
|
||||
/// Called by SaveLoadManager during initial boot load.
|
||||
/// </summary>
|
||||
public void BroadcastGlobalRestoreRequested(Dictionary<string, string> saveData)
|
||||
{
|
||||
if (saveData == null) return;
|
||||
|
||||
int restoredCount = 0;
|
||||
|
||||
// Create a copy to avoid collection modification during iteration
|
||||
var componentsCopy = new List<ManagedBehaviour>(managedAwakeList);
|
||||
|
||||
foreach (var component in componentsCopy)
|
||||
{
|
||||
if (component == null || !component.AutoRegisterForSave) continue;
|
||||
|
||||
if (saveData.TryGetValue(component.SaveId, out string serializedData))
|
||||
{
|
||||
try
|
||||
{
|
||||
component.InvokeGlobalRestoreRequested(serializedData);
|
||||
restoredCount++;
|
||||
LogDebug($"Restored global data to: {component.SaveId}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Debug.LogError($"[LifecycleManager] Exception during global restore for {component.SaveId}: {ex}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
LogDebug($"Restored global data to {restoredCount} components");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Broadcasts global load completed event to all registered components that opt-in.
|
||||
/// Called ONCE after save file is successfully loaded on game boot.
|
||||
/// NOT called during scene transitions.
|
||||
/// </summary>
|
||||
public void BroadcastGlobalLoadCompleted()
|
||||
{
|
||||
LogDebug("Broadcasting GlobalLoadCompleted");
|
||||
|
||||
// Create a copy to avoid collection modification during iteration
|
||||
var componentsCopy = new List<ManagedBehaviour>(managedAwakeList);
|
||||
|
||||
foreach (var component in componentsCopy)
|
||||
{
|
||||
if (component == null || !component.AutoRegisterForSave) continue;
|
||||
|
||||
try
|
||||
{
|
||||
component.InvokeGlobalLoadCompleted();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Debug.LogError($"[LifecycleManager] Exception during global load for {component.name}: {ex}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Broadcasts global save started event to all registered components that opt-in.
|
||||
/// Called ONCE before save file is written to disk.
|
||||
/// NOT called during scene transitions.
|
||||
/// </summary>
|
||||
public void BroadcastGlobalSaveStarted()
|
||||
{
|
||||
LogDebug("Broadcasting GlobalSaveStarted");
|
||||
|
||||
// Create a copy to avoid collection modification during iteration
|
||||
var componentsCopy = new List<ManagedBehaviour>(managedAwakeList);
|
||||
|
||||
foreach (var component in componentsCopy)
|
||||
{
|
||||
if (component == null || !component.AutoRegisterForSave) continue;
|
||||
|
||||
try
|
||||
{
|
||||
component.InvokeGlobalSaveStarted();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Debug.LogError($"[LifecycleManager] Exception during global save for {component.name}: {ex}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Auto-Registration
|
||||
|
||||
/// <summary>
|
||||
/// Handle automatic registration with GameManager.
|
||||
/// </summary>
|
||||
private void HandleAutoRegistrations(ManagedBehaviour component)
|
||||
{
|
||||
|
||||
// Auto-register IPausable
|
||||
if (component.AutoRegisterPausable && component is AppleHills.Core.Interfaces.IPausable pausable)
|
||||
{
|
||||
if (GameManager.Instance != null)
|
||||
{
|
||||
GameManager.Instance.RegisterPausableComponent(pausable);
|
||||
LogDebug($"Auto-registered IPausable: {component.gameObject.name}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Helper Methods
|
||||
|
||||
/// <summary>
|
||||
/// Insert component into list maintaining sorted order by priority.
|
||||
/// Uses binary search for efficient insertion.
|
||||
/// </summary>
|
||||
private void InsertSorted(List<ManagedBehaviour> list, ManagedBehaviour component, int priority)
|
||||
{
|
||||
// Simple linear insertion for now (can optimize with binary search later if needed)
|
||||
int index = 0;
|
||||
for (int i = 0; i < list.Count; i++)
|
||||
{
|
||||
int existingPriority = GetPriorityForList(list[i], list);
|
||||
if (priority < existingPriority)
|
||||
{
|
||||
index = i;
|
||||
break;
|
||||
}
|
||||
index = i + 1;
|
||||
}
|
||||
|
||||
list.Insert(index, component);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Get the priority value for a component based on which list it's in.
|
||||
/// </summary>
|
||||
private int GetPriorityForList(ManagedBehaviour component, List<ManagedBehaviour> list)
|
||||
{
|
||||
if (list == managedAwakeList) return component.ManagedAwakePriority;
|
||||
if (list == sceneUnloadingList) return component.SceneUnloadingPriority;
|
||||
if (list == sceneReadyList) return component.SceneReadyPriority;
|
||||
if (list == saveRequestedList) return component.SavePriority;
|
||||
if (list == restoreRequestedList) return component.RestorePriority;
|
||||
if (list == destroyList) return component.DestroyPriority;
|
||||
return 100;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Log debug message if debug logging is enabled.
|
||||
/// </summary>
|
||||
private void LogDebug(string message)
|
||||
{
|
||||
if (enableDebugLogging)
|
||||
{
|
||||
Debug.Log($"[LifecycleManager] {message}");
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
|
||||
2
Assets/Scripts/Core/Lifecycle/LifecycleManager.cs.meta
Normal file
2
Assets/Scripts/Core/Lifecycle/LifecycleManager.cs.meta
Normal file
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: db6d4743867a3a44381d511cea39218d
|
||||
288
Assets/Scripts/Core/Lifecycle/ManagedBehaviour.cs
Normal file
288
Assets/Scripts/Core/Lifecycle/ManagedBehaviour.cs
Normal file
@@ -0,0 +1,288 @@
|
||||
using System;
|
||||
using UnityEngine;
|
||||
|
||||
namespace Core.Lifecycle
|
||||
{
|
||||
/// <summary>
|
||||
/// Base class for all managed behaviours with deterministic lifecycle hooks.
|
||||
/// Automatically registers with LifecycleManager and provides ordered lifecycle callbacks.
|
||||
/// </summary>
|
||||
public abstract class ManagedBehaviour : MonoBehaviour
|
||||
{
|
||||
#region Priority Properties
|
||||
|
||||
/// <summary>
|
||||
/// Priority for OnManagedAwake (lower values execute first).
|
||||
/// Default: 100
|
||||
/// </summary>
|
||||
public virtual int ManagedAwakePriority => 100;
|
||||
|
||||
/// <summary>
|
||||
/// Priority for OnSceneUnloading (executed in reverse: higher values execute first).
|
||||
/// Default: 100
|
||||
/// </summary>
|
||||
public virtual int SceneUnloadingPriority => 100;
|
||||
|
||||
/// <summary>
|
||||
/// Priority for OnSceneReady (lower values execute first).
|
||||
/// Default: 100
|
||||
/// </summary>
|
||||
public virtual int SceneReadyPriority => 100;
|
||||
|
||||
/// <summary>
|
||||
/// Priority for OnSaveRequested (executed in reverse: higher values execute first).
|
||||
/// Default: 100
|
||||
/// </summary>
|
||||
public virtual int SavePriority => 100;
|
||||
|
||||
/// <summary>
|
||||
/// Priority for OnRestoreRequested (lower values execute first).
|
||||
/// Default: 100
|
||||
/// </summary>
|
||||
public virtual int RestorePriority => 100;
|
||||
|
||||
/// <summary>
|
||||
/// Priority for OnManagedDestroy (executed in reverse: higher values execute first).
|
||||
/// Default: 100
|
||||
/// </summary>
|
||||
public virtual int DestroyPriority => 100;
|
||||
|
||||
#endregion
|
||||
|
||||
#region Configuration Properties
|
||||
|
||||
/// <summary>
|
||||
/// If true and component implements IPausable, automatically registers with GameManager.
|
||||
/// Default: false
|
||||
/// </summary>
|
||||
public virtual bool AutoRegisterPausable => false;
|
||||
|
||||
/// <summary>
|
||||
/// If true, this component participates in the save/load system.
|
||||
/// Components should override OnSaveRequested() and OnRestoreRequested().
|
||||
/// Default: false
|
||||
/// </summary>
|
||||
public virtual bool AutoRegisterForSave => false;
|
||||
|
||||
/// <summary>
|
||||
/// Unique identifier for this component in the save system.
|
||||
/// Default: "SceneName/GameObjectName/ComponentType"
|
||||
/// Override ONLY for special cases (e.g., singletons like "PlayerController", or custom IDs).
|
||||
/// </summary>
|
||||
public virtual string SaveId
|
||||
{
|
||||
get
|
||||
{
|
||||
string sceneName = gameObject.scene.IsValid() ? gameObject.scene.name : "UnknownScene";
|
||||
string componentType = GetType().Name;
|
||||
return $"{sceneName}/{gameObject.name}/{componentType}";
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Public Accessors (for LifecycleManager)
|
||||
|
||||
// Public wrappers to invoke protected lifecycle methods
|
||||
public void InvokeManagedAwake() => OnManagedAwake();
|
||||
public void InvokeSceneUnloading() => OnSceneUnloading();
|
||||
public void InvokeSceneReady() => OnSceneReady();
|
||||
public string InvokeSceneSaveRequested() => OnSceneSaveRequested();
|
||||
public void InvokeSceneRestoreRequested(string data) => OnSceneRestoreRequested(data);
|
||||
public string InvokeGlobalSaveRequested() => OnGlobalSaveRequested();
|
||||
public void InvokeGlobalRestoreRequested(string data) => OnGlobalRestoreRequested(data);
|
||||
public void InvokeManagedDestroy() => OnManagedDestroy();
|
||||
public void InvokeGlobalLoadCompleted() => OnGlobalLoadCompleted();
|
||||
public void InvokeGlobalSaveStarted() => OnGlobalSaveStarted();
|
||||
|
||||
#endregion
|
||||
|
||||
#region Private Fields
|
||||
|
||||
private bool _isRegistered;
|
||||
|
||||
#endregion
|
||||
|
||||
#region Unity Lifecycle
|
||||
|
||||
/// <summary>
|
||||
/// Unity Awake - automatically registers with LifecycleManager.
|
||||
/// IMPORTANT: Derived classes that override Awake MUST call base.Awake()
|
||||
/// </summary>
|
||||
protected virtual void Awake()
|
||||
{
|
||||
if (LifecycleManager.Instance != null)
|
||||
{
|
||||
LifecycleManager.Instance.Register(this);
|
||||
_isRegistered = true;
|
||||
}
|
||||
else
|
||||
{
|
||||
Debug.LogWarning($"[ManagedBehaviour] LifecycleManager not found for {gameObject.name}. Component will not receive lifecycle callbacks.");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Unity OnDestroy - automatically unregisters and cleans up.
|
||||
/// IMPORTANT: Derived classes that override OnDestroy MUST call base.OnDestroy()
|
||||
/// </summary>
|
||||
protected virtual void OnDestroy()
|
||||
{
|
||||
if (!_isRegistered)
|
||||
return;
|
||||
|
||||
// Unregister from LifecycleManager
|
||||
if (LifecycleManager.Instance != null)
|
||||
{
|
||||
LifecycleManager.Instance.Unregister(this);
|
||||
}
|
||||
|
||||
|
||||
// Auto-unregister from GameManager if auto-registered
|
||||
if (AutoRegisterPausable && this is AppleHills.Core.Interfaces.IPausable pausable)
|
||||
{
|
||||
GameManager.Instance?.UnregisterPausableComponent(pausable);
|
||||
}
|
||||
|
||||
_isRegistered = false;
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Managed Lifecycle Hooks
|
||||
|
||||
/// <summary>
|
||||
/// Called once per component after bootstrap completes.
|
||||
/// GUARANTEE: Bootstrap resources are available, all managers are initialized.
|
||||
/// For boot-time components: Called during LifecycleManager.BroadcastManagedAwake (priority ordered).
|
||||
/// For late-registered components: Called immediately upon registration (bootstrap already complete).
|
||||
/// Replaces the old Awake + InitializePostBoot pattern.
|
||||
/// </summary>
|
||||
protected virtual void OnManagedAwake()
|
||||
{
|
||||
// Override in derived classes
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Called before the scene this component belongs to is unloaded.
|
||||
/// Called in REVERSE priority order (higher values execute first).
|
||||
/// Use for scene-specific cleanup.
|
||||
/// </summary>
|
||||
protected virtual void OnSceneUnloading()
|
||||
{
|
||||
// Override in derived classes
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Called after the scene this component belongs to has finished loading.
|
||||
/// Called in priority order (lower values execute first).
|
||||
/// Use for scene-specific initialization.
|
||||
/// </summary>
|
||||
protected virtual void OnSceneReady()
|
||||
{
|
||||
// Override in derived classes
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Called during scene transitions to save scene-specific state.
|
||||
/// Return serialized data (e.g., JsonUtility.ToJson(myData)).
|
||||
/// Return null if component has no scene-specific state to save.
|
||||
///
|
||||
/// TIMING:
|
||||
/// - Called BEFORE scene unload during scene transitions
|
||||
/// - Frequency: Every scene transition
|
||||
/// - Use for: Level progress, object positions, puzzle states
|
||||
/// </summary>
|
||||
protected virtual string OnSceneSaveRequested()
|
||||
{
|
||||
return null; // Default: no data to save
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Called during scene transitions to restore scene-specific state.
|
||||
/// Receives previously serialized data (from OnSceneSaveRequested).
|
||||
///
|
||||
/// TIMING:
|
||||
/// - Called AFTER scene load, during OnSceneReady phase
|
||||
/// - Frequency: Every scene transition
|
||||
/// - Use for: Restoring level progress, object positions, puzzle states
|
||||
/// </summary>
|
||||
protected virtual void OnSceneRestoreRequested(string serializedData)
|
||||
{
|
||||
// Default: no-op
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Called once on game boot to restore global persistent state.
|
||||
/// Receives data that was saved via OnGlobalSaveRequested.
|
||||
///
|
||||
/// TIMING:
|
||||
/// - Called ONCE on game boot after save file is read
|
||||
/// - NOT called during scene transitions
|
||||
/// - Use for: Player inventory, unlocked features, card collections
|
||||
/// </summary>
|
||||
protected virtual void OnGlobalRestoreRequested(string serializedData)
|
||||
{
|
||||
// Default: no-op
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Called once before game save file is written to disk.
|
||||
/// Return serialized data for global persistent state.
|
||||
/// Return null if component has no global state to save.
|
||||
///
|
||||
/// TIMING:
|
||||
/// - Called ONCE before save file is written (on quit, manual save, etc.)
|
||||
/// - NOT called during scene transitions
|
||||
/// - Use for: Player inventory, unlocked features, card collections
|
||||
/// </summary>
|
||||
protected virtual string OnGlobalSaveRequested()
|
||||
{
|
||||
return null; // Default: no data to save
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Called once when game save data is initially loaded from disk.
|
||||
/// Use for global managers that need to react to load completion.
|
||||
/// Does NOT receive data - use OnGlobalRestoreRequested for that.
|
||||
///
|
||||
/// TIMING:
|
||||
/// - Called ONCE on game boot after all restore operations complete
|
||||
/// - NOT called during scene transitions
|
||||
/// - Use for: Triggering UI updates, broadcasting load events
|
||||
/// </summary>
|
||||
protected virtual void OnGlobalLoadCompleted()
|
||||
{
|
||||
// Default: no-op
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Called once before save file is written to disk.
|
||||
/// Use for global managers that need to perform cleanup before save.
|
||||
/// Does NOT return data - use OnGlobalSaveRequested for that.
|
||||
///
|
||||
/// TIMING:
|
||||
/// - Called ONCE before save file is written
|
||||
/// - NOT called during scene transitions
|
||||
/// - Use for: Final validation, cleanup operations
|
||||
/// </summary>
|
||||
protected virtual void OnGlobalSaveStarted()
|
||||
{
|
||||
// Default: no-op
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Called during OnDestroy before component is destroyed.
|
||||
/// Called in REVERSE priority order (higher values execute first).
|
||||
/// NOTE: Most cleanup is automatic (managed events, auto-registrations).
|
||||
/// Only override if you need custom cleanup logic.
|
||||
/// </summary>
|
||||
protected virtual void OnManagedDestroy()
|
||||
{
|
||||
// Override in derived classes
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
|
||||
2
Assets/Scripts/Core/Lifecycle/ManagedBehaviour.cs.meta
Normal file
2
Assets/Scripts/Core/Lifecycle/ManagedBehaviour.cs.meta
Normal file
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: af776ef1493d6e543aa3cbe2601f4ef2
|
||||
Reference in New Issue
Block a user