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:
2025-11-07 15:38:31 +00:00
parent dfa42b2296
commit e27bb7bfb6
93 changed files with 7900 additions and 4347 deletions

View File

@@ -2,6 +2,7 @@
using Interactions;
using UnityEngine;
using Core;
using Core.Lifecycle;
namespace PuzzleS
{
@@ -9,7 +10,7 @@ namespace PuzzleS
/// Manages the state and interactions for a single puzzle step, including unlock/lock logic and event handling.
/// </summary>
[RequireComponent(typeof(InteractableBase))]
public class ObjectiveStepBehaviour : MonoBehaviour, IPuzzlePrompt
public class ObjectiveStepBehaviour : ManagedBehaviour, IPuzzlePrompt
{
/// <summary>
/// The data object representing this puzzle step.
@@ -31,7 +32,7 @@ namespace PuzzleS
// Enum for tracking proximity state (simplified to just Close and Far)
public enum ProximityState { Close, Far }
void Awake()
protected override void Awake()
{
_interactable = GetComponent<InteractableBase>();
@@ -55,6 +56,23 @@ namespace PuzzleS
Logging.Warning($"[Puzzles] Indicator prefab for {stepData?.stepId} does not implement IPuzzlePrompt");
}
}
base.Awake();
}
protected override void OnManagedAwake()
{
base.OnManagedAwake();
// Register with PuzzleManager - safe to access .Instance here
if (stepData != null && PuzzleManager.Instance != null)
{
PuzzleManager.Instance.RegisterStepBehaviour(this);
}
else if (stepData == null)
{
Logging.Warning($"[Puzzles] Cannot register step on {gameObject.name}: stepData is null");
}
}
void OnEnable()
@@ -68,33 +86,21 @@ namespace PuzzleS
_interactable.interactionComplete.AddListener(OnInteractionComplete);
}
}
void Start()
protected override void OnDestroy()
{
// Simply register with the PuzzleManager
// The manager will handle state updates appropriately based on whether data is loaded
if (stepData != null && PuzzleManager.Instance != null)
{
PuzzleManager.Instance.RegisterStepBehaviour(this);
}
else if (stepData == null)
{
Logging.Warning($"[Puzzles] Cannot register step on {gameObject.name}: stepData is null");
}
}
void OnDestroy()
{
if (_interactable != null)
{
_interactable.interactionStarted.RemoveListener(OnInteractionStarted);
_interactable.interactionComplete.RemoveListener(OnInteractionComplete);
}
base.OnDestroy();
if (PuzzleManager.Instance != null && stepData != null)
{
PuzzleManager.Instance.UnregisterStepBehaviour(this);
}
if (_interactable != null)
{
_interactable.interactionStarted.RemoveListener(OnInteractionStarted);
_interactable.interactionComplete.RemoveListener(OnInteractionComplete);
}
}
/// <summary>

View File

@@ -5,9 +5,8 @@ using System.Linq;
using UnityEngine;
using UnityEngine.SceneManagement;
using AppleHills.Core.Settings;
using Bootstrap;
using Core;
using Core.SaveLoad;
using Core.Lifecycle;
using UnityEngine.AddressableAssets;
using UnityEngine.ResourceManagement.AsyncOperations;
using Utils;
@@ -28,7 +27,7 @@ namespace PuzzleS
/// <summary>
/// Manages puzzle step registration, dependency management, and step completion for the puzzle system.
/// </summary>
public class PuzzleManager : MonoBehaviour, ISaveParticipant
public class PuzzleManager : ManagedBehaviour
{
private static PuzzleManager _instance;
@@ -49,6 +48,27 @@ namespace PuzzleS
// Store registered behaviors that are waiting for data to be loaded
private List<ObjectiveStepBehaviour> _registeredBehaviours = new List<ObjectiveStepBehaviour>();
// Save system configuration
public override bool AutoRegisterForSave => true;
/// <summary>
/// SaveId uses CurrentGameplayScene instead of GetActiveScene() because PuzzleManager
/// lives in DontDestroyOnLoad and needs to save/load data per-scene.
/// </summary>
public override string SaveId
{
get
{
string sceneName = SceneManagerService.Instance?.CurrentGameplayScene;
if (string.IsNullOrEmpty(sceneName))
{
// Fallback during early initialization
sceneName = SceneManager.GetActiveScene().name;
}
return $"{sceneName}/PuzzleManager";
}
}
/// <summary>
/// Singleton instance of the PuzzleManager.
/// </summary>
@@ -66,7 +86,6 @@ namespace PuzzleS
// Save/Load restoration tracking
private bool _isDataRestored = false;
private bool _hasBeenRestored = false;
private List<ObjectiveStepBehaviour> _pendingRegistrations = new List<ObjectiveStepBehaviour>();
// Registration for ObjectiveStepBehaviour
@@ -74,36 +93,21 @@ namespace PuzzleS
// Track pending unlocks for steps that were unlocked before their behavior registered
private HashSet<string> _pendingUnlocks = new HashSet<string>();
/// <summary>
/// Returns true if this participant has already had its state restored.
/// Used by SaveLoadManager to prevent double-restoration.
/// </summary>
public bool HasBeenRestored => _hasBeenRestored;
void Awake()
public override int ManagedAwakePriority => 80; // Puzzle systems
private new void Awake()
{
base.Awake(); // CRITICAL: Register with LifecycleManager!
// Set instance immediately so it's available before OnManagedAwake() is called
_instance = this;
// Initialize settings reference
_interactionSettings = GameManager.GetSettingsObject<IInteractionSettings>();
// Register for post-boot initialization
BootCompletionService.RegisterInitAction(InitializePostBoot);
}
private void InitializePostBoot()
protected override void OnManagedAwake()
{
// Subscribe to SceneManagerService events after boot is complete
SceneManagerService.Instance.SceneLoadCompleted += OnSceneLoadCompleted;
SceneManagerService.Instance.SceneLoadStarted += OnSceneLoadStarted;
// Register with save/load system
BootCompletionService.RegisterInitAction(() =>
{
SaveLoadManager.Instance.RegisterParticipant(this);
Logging.Debug("[PuzzleManager] Registered with SaveLoadManager");
});
// Initialize settings reference
_interactionSettings = GameManager.GetSettingsObject<IInteractionSettings>();
// Find player transform
_playerTransform = GameObject.FindGameObjectWithTag("Player")?.transform;
@@ -117,46 +121,40 @@ namespace PuzzleS
LoadPuzzleDataForCurrentScene();
}
Logging.Debug("[PuzzleManager] Subscribed to SceneManagerService events");
// Subscribe to scene load events from SceneManagerService
// This is necessary because PuzzleManager is in DontDestroyOnLoad and won't receive OnSceneReady() callbacks
if (SceneManagerService.Instance != null)
{
SceneManagerService.Instance.SceneLoadCompleted += OnSceneLoadCompleted;
}
Logging.Debug("[PuzzleManager] Initialized");
}
void OnDestroy()
/// <summary>
/// Called when any scene finishes loading. Loads puzzles for the new scene.
/// </summary>
private void OnSceneLoadCompleted(string sceneName)
{
StopProximityChecks();
Logging.Debug($"[Puzzles] Scene loaded: {sceneName}, loading puzzle data");
LoadPuzzlesForScene(sceneName);
}
protected override void OnDestroy()
{
base.OnDestroy();
// Unsubscribe from scene manager events
// Unsubscribe from SceneManagerService events
if (SceneManagerService.Instance != null)
{
SceneManagerService.Instance.SceneLoadCompleted -= OnSceneLoadCompleted;
SceneManagerService.Instance.SceneLoadStarted -= OnSceneLoadStarted;
}
// Unregister from save/load system
SaveLoadManager.Instance.UnregisterParticipant(GetSaveId());
Logging.Debug("[PuzzleManager] Unregistered from SaveLoadManager");
// Release addressable handle if needed
if (_levelDataLoadOperation.IsValid())
{
Addressables.Release(_levelDataLoadOperation);
}
}
/// <summary>
/// Called when a scene is starting to load
/// Loads puzzle data for the specified scene
/// </summary>
public void OnSceneLoadStarted(string sceneName)
{
// Reset data loaded state when changing scenes to avoid using stale data
_isDataLoaded = false;
Logging.Debug($"[Puzzles] Scene load started: {sceneName}, marked puzzle data as not loaded");
}
/// <summary>
/// Called when a scene is loaded
/// </summary>
public void OnSceneLoadCompleted(string sceneName)
private void LoadPuzzlesForScene(string sceneName)
{
// Skip for non-gameplay scenes
if (sceneName == "BootstrapScene" || string.IsNullOrEmpty(sceneName))
@@ -186,6 +184,8 @@ namespace PuzzleS
return;
}
// Reset restoration flag when loading new scene data
_isDataRestored = false;
_isDataLoaded = false;
string addressablePath = $"Puzzles/{currentScene}";
@@ -215,11 +215,10 @@ namespace PuzzleS
_currentLevelData = handle.Result;
Logging.Debug($"[Puzzles] Loaded level data: {_currentLevelData.levelId} with {_currentLevelData.allSteps.Count} steps");
// Reset state
_completedSteps.Clear();
_unlockedSteps.Clear();
// Don't clear steps here - SceneManagerService calls ClearPuzzleState() before scene transitions
// This allows save restoration to work properly without race conditions
// Unlock initial steps
// Unlock initial steps (adds to existing unlocked steps from save restoration)
UnlockInitialSteps();
// Update all registered behaviors now that data is loaded
@@ -569,21 +568,30 @@ namespace PuzzleS
return _isDataLoaded;
}
#region ISaveParticipant Implementation
/// <summary>
/// Get unique save ID for this puzzle manager instance
/// Clears all puzzle state (completed steps, unlocked steps, registrations).
/// Called by SceneManagerService before scene transitions to ensure clean state.
/// </summary>
public string GetSaveId()
public void ClearPuzzleState()
{
string sceneName = SceneManager.GetActiveScene().name;
return $"{sceneName}/PuzzleManager";
Logging.Debug("[PuzzleManager] Clearing puzzle state");
_completedSteps.Clear();
_unlockedSteps.Clear();
_isDataRestored = false;
// Clear any pending registrations from the old scene
_pendingRegistrations.Clear();
_pendingUnlocks.Clear();
// Unregister all step behaviours from the old scene
_stepBehaviours.Clear();
_registeredBehaviours.Clear();
}
/// <summary>
/// Serialize current puzzle state to JSON
/// </summary>
public string SerializeState()
#region Save/Load Lifecycle Hooks
protected override string OnSceneSaveRequested()
{
if (_currentLevelData == null)
{
@@ -603,16 +611,14 @@ namespace PuzzleS
return json;
}
/// <summary>
/// Restore puzzle state from serialized JSON data
/// </summary>
public void RestoreState(string data)
protected override void OnSceneRestoreRequested(string data)
{
Debug.Log("[XAXA] PuzzleManager loading with data: " + data);
if (string.IsNullOrEmpty(data) || data == "{}")
{
Logging.Debug("[PuzzleManager] No puzzle save data to restore");
_isDataRestored = true;
_hasBeenRestored = true;
return;
}
@@ -623,7 +629,6 @@ namespace PuzzleS
{
Logging.Warning("[PuzzleManager] Failed to deserialize puzzle save data");
_isDataRestored = true;
_hasBeenRestored = true;
return;
}
@@ -632,14 +637,14 @@ namespace PuzzleS
_unlockedSteps = new HashSet<string>(saveData.unlockedStepIds ?? new List<string>());
_isDataRestored = true;
_hasBeenRestored = true;
Logging.Debug($"[PuzzleManager] Restored puzzle state: {_completedSteps.Count} completed, {_unlockedSteps.Count} unlocked steps");
// Update any behaviors that registered before RestoreState was called
foreach (var behaviour in _pendingRegistrations)
{
UpdateStepState(behaviour);
if(behaviour != null)
UpdateStepState(behaviour);
}
_pendingRegistrations.Clear();
}
@@ -647,7 +652,6 @@ namespace PuzzleS
{
Debug.LogError($"[PuzzleManager] Error restoring puzzle state: {e.Message}");
_isDataRestored = true;
_hasBeenRestored = true;
}
}