# 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
352 lines
12 KiB
C#
352 lines
12 KiB
C#
using Input;
|
|
using Interactions;
|
|
using UnityEngine;
|
|
using Core;
|
|
using Core.Lifecycle;
|
|
|
|
namespace PuzzleS
|
|
{
|
|
/// <summary>
|
|
/// Manages the state and interactions for a single puzzle step, including unlock/lock logic and event handling.
|
|
/// </summary>
|
|
[RequireComponent(typeof(InteractableBase))]
|
|
public class ObjectiveStepBehaviour : ManagedBehaviour, IPuzzlePrompt
|
|
{
|
|
/// <summary>
|
|
/// The data object representing this puzzle step.
|
|
/// </summary>
|
|
public PuzzleStepSO stepData;
|
|
|
|
[Header("Indicator Settings")]
|
|
[SerializeField] private GameObject puzzleIndicator;
|
|
[SerializeField] private bool drawPromptRangeGizmo = true;
|
|
|
|
private InteractableBase _interactable;
|
|
private bool _isUnlocked = false;
|
|
private bool _isCompleted = false;
|
|
private IPuzzlePrompt _indicator;
|
|
|
|
// Current proximity state tracked by PuzzleManager
|
|
private ProximityState _currentProximityState = ProximityState.Far;
|
|
|
|
// Enum for tracking proximity state (simplified to just Close and Far)
|
|
public enum ProximityState { Close, Far }
|
|
|
|
protected override void Awake()
|
|
{
|
|
_interactable = GetComponent<InteractableBase>();
|
|
|
|
// Initialize the indicator if it exists, but ensure it's hidden initially
|
|
if (puzzleIndicator != null)
|
|
{
|
|
// The indicator should start inactive until we determine its proper state
|
|
puzzleIndicator.SetActive(false);
|
|
|
|
// Get the IPuzzlePrompt component
|
|
_indicator = puzzleIndicator.GetComponent<IPuzzlePrompt>();
|
|
|
|
if (_indicator == null)
|
|
{
|
|
// Try to find it in children if not on the root
|
|
_indicator = puzzleIndicator.GetComponentInChildren<IPuzzlePrompt>();
|
|
}
|
|
|
|
if (_indicator == null)
|
|
{
|
|
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()
|
|
{
|
|
if (_interactable == null)
|
|
_interactable = GetComponent<InteractableBase>();
|
|
|
|
if (_interactable != null)
|
|
{
|
|
_interactable.interactionStarted.AddListener(OnInteractionStarted);
|
|
_interactable.interactionComplete.AddListener(OnInteractionComplete);
|
|
}
|
|
}
|
|
|
|
protected override void OnDestroy()
|
|
{
|
|
base.OnDestroy();
|
|
|
|
if (PuzzleManager.Instance != null && stepData != null)
|
|
{
|
|
PuzzleManager.Instance.UnregisterStepBehaviour(this);
|
|
}
|
|
|
|
if (_interactable != null)
|
|
{
|
|
_interactable.interactionStarted.RemoveListener(OnInteractionStarted);
|
|
_interactable.interactionComplete.RemoveListener(OnInteractionComplete);
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Updates the proximity state from PuzzleManager and triggers appropriate methods.
|
|
/// </summary>
|
|
/// <param name="newState">The new proximity state.</param>
|
|
public void UpdateProximityState(ProximityState newState)
|
|
{
|
|
if (_currentProximityState == newState) return;
|
|
if (!_isUnlocked) return; // Don't process state changes if locked
|
|
|
|
// Determine state changes and call appropriate methods
|
|
if (newState == ProximityState.Close)
|
|
{
|
|
// Transitioning from Far to Close
|
|
ShowClose();
|
|
}
|
|
else // newState == ProximityState.Far
|
|
{
|
|
// Transitioning from Close to Far
|
|
HideClose();
|
|
}
|
|
|
|
_currentProximityState = newState;
|
|
}
|
|
|
|
// IPuzzlePrompt interface implementation - delegates to indicator if available
|
|
|
|
/// <summary>
|
|
/// Called when the prompt should be initially shown (e.g., when step is unlocked)
|
|
/// </summary>
|
|
public virtual void OnShow()
|
|
{
|
|
if (puzzleIndicator != null)
|
|
puzzleIndicator.SetActive(true);
|
|
|
|
// Delegate to indicator if available
|
|
if (IsIndicatorValid())
|
|
{
|
|
_indicator.OnShow();
|
|
return;
|
|
}
|
|
|
|
Logging.Debug($"[Puzzles] Prompt shown for {stepData?.stepId} on {gameObject.name}");
|
|
}
|
|
|
|
/// <summary>
|
|
/// Called when the prompt should be hidden (e.g., when step is locked)
|
|
/// </summary>
|
|
public virtual void OnHide()
|
|
{
|
|
if (puzzleIndicator != null)
|
|
puzzleIndicator.SetActive(false);
|
|
|
|
// Delegate to indicator if available
|
|
if (IsIndicatorValid())
|
|
{
|
|
_indicator.OnHide();
|
|
}
|
|
|
|
Logging.Debug($"[Puzzles] Prompt hidden for {stepData?.stepId} on {gameObject.name}");
|
|
}
|
|
|
|
/// <summary>
|
|
/// Called when player enters the far range
|
|
/// </summary>
|
|
public virtual void ShowFar()
|
|
{
|
|
// Only show if step is unlocked
|
|
if (!_isUnlocked) return;
|
|
|
|
// Delegate to indicator if available
|
|
if (IsIndicatorValid())
|
|
{
|
|
_indicator.ShowFar();
|
|
return;
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Called when player enters the close range
|
|
/// </summary>
|
|
public virtual void ShowClose()
|
|
{
|
|
// Only show if step is unlocked
|
|
if (!_isUnlocked) return;
|
|
|
|
// Delegate to indicator if available
|
|
if (IsIndicatorValid())
|
|
{
|
|
_indicator.ShowClose();
|
|
return;
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Called when player exits the close range
|
|
/// </summary>
|
|
public virtual void HideClose()
|
|
{
|
|
// Only respond if step is unlocked
|
|
if (!_isUnlocked) return;
|
|
|
|
// Delegate to indicator if available
|
|
if (IsIndicatorValid())
|
|
{
|
|
_indicator.HideClose();
|
|
return;
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Called when player exits the far range
|
|
/// </summary>
|
|
public virtual void HideFar()
|
|
{
|
|
// Only respond if step is unlocked
|
|
if (!_isUnlocked) return;
|
|
|
|
// Delegate to indicator if available
|
|
if (IsIndicatorValid())
|
|
{
|
|
_indicator.HideFar();
|
|
return;
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Unlocks this puzzle step, allowing interaction.
|
|
/// </summary>
|
|
public void UnlockStep()
|
|
{
|
|
if (_isUnlocked) return;
|
|
|
|
_isUnlocked = true;
|
|
Logging.Debug($"[Puzzles] Step unlocked: {stepData?.stepId} on {gameObject.name}");
|
|
|
|
// Make the indicator visible since this step is now unlocked
|
|
OnShow();
|
|
|
|
if (IsIndicatorValid())
|
|
{
|
|
// Set the correct state based on current player distance
|
|
Transform playerTransform = GameObject.FindGameObjectWithTag("Player")?.transform;
|
|
if (playerTransform != null)
|
|
{
|
|
float distance = Vector3.Distance(transform.position, playerTransform.position);
|
|
float promptRange = AppleHills.SettingsAccess.GetPuzzlePromptRange();
|
|
|
|
if (distance <= promptRange)
|
|
{
|
|
// Player is in close range
|
|
_currentProximityState = ProximityState.Close;
|
|
_indicator.ShowClose();
|
|
}
|
|
else
|
|
{
|
|
// Player is in far range
|
|
_currentProximityState = ProximityState.Far;
|
|
_indicator.ShowFar();
|
|
}
|
|
}
|
|
else
|
|
{
|
|
// Default to far if player not found
|
|
_currentProximityState = ProximityState.Far;
|
|
_indicator.ShowFar();
|
|
}
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Locks this puzzle step, preventing interaction.
|
|
/// </summary>
|
|
public void LockStep()
|
|
{
|
|
if (!_isUnlocked && puzzleIndicator != null)
|
|
{
|
|
// Make sure indicator is hidden if we're already locked
|
|
puzzleIndicator.SetActive(false);
|
|
return;
|
|
}
|
|
|
|
_isUnlocked = false;
|
|
Logging.Debug($"[Puzzles] Step locked: {stepData?.stepId} on {gameObject.name}");
|
|
|
|
// Hide the indicator
|
|
OnHide();
|
|
}
|
|
|
|
/// <summary>
|
|
/// Returns whether this step is currently unlocked.
|
|
/// </summary>
|
|
public bool IsStepUnlocked()
|
|
{
|
|
return _isUnlocked;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Handles the start of an interaction (can be used for visual feedback).
|
|
/// </summary>
|
|
private void OnInteractionStarted(PlayerTouchController playerRef, FollowerController followerRef)
|
|
{
|
|
// Empty - handled by Interactable
|
|
}
|
|
|
|
/// <summary>
|
|
/// Handles completion of the interaction, notifies PuzzleManager if successful and unlocked.
|
|
/// </summary>
|
|
/// <param name="success">Whether the interaction was successful.</param>
|
|
private void OnInteractionComplete(bool success)
|
|
{
|
|
if (!_isUnlocked) return;
|
|
if (success && !_isCompleted)
|
|
{
|
|
Logging.Debug($"[Puzzles] Step interacted: {stepData?.stepId} on {gameObject.name}");
|
|
_isCompleted = true;
|
|
PuzzleManager.Instance?.MarkPuzzleStepCompleted(stepData);
|
|
|
|
if (puzzleIndicator != null)
|
|
{
|
|
Destroy(puzzleIndicator);
|
|
_indicator = null;
|
|
}
|
|
}
|
|
}
|
|
|
|
private bool IsIndicatorValid()
|
|
{
|
|
return _indicator != null && puzzleIndicator != null && !_isCompleted;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Visualizes the puzzle prompt ranges in the editor.
|
|
/// </summary>
|
|
private void OnDrawGizmos()
|
|
{
|
|
if (!drawPromptRangeGizmo) return;
|
|
|
|
// Use the global puzzle prompt range from settings
|
|
float promptRange = AppleHills.SettingsAccess.GetPuzzlePromptRange();
|
|
|
|
// Draw threshold circle
|
|
Gizmos.color = Color.cyan;
|
|
Gizmos.DrawWireSphere(transform.position, promptRange);
|
|
}
|
|
}
|
|
}
|