# 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
289 lines
12 KiB
C#
289 lines
12 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using AppleHills.Core.Interfaces;
|
|
using AppleHills.Core.Settings;
|
|
using Core.Lifecycle;
|
|
using Core.Settings;
|
|
using Input;
|
|
using UnityEngine;
|
|
|
|
namespace Core
|
|
{
|
|
/// <summary>
|
|
/// Singleton manager for global game state and settings. Provides accessors for various gameplay parameters.
|
|
/// </summary>
|
|
public class GameManager : ManagedBehaviour
|
|
{
|
|
// Singleton implementation
|
|
private static GameManager _instance;
|
|
public static GameManager Instance => _instance;
|
|
|
|
private bool _settingsLoaded;
|
|
private bool _developerSettingsLoaded;
|
|
|
|
// Pausable implementation (counter-based)
|
|
private int _pauseCount;
|
|
public bool IsPaused => _pauseCount > 0;
|
|
|
|
// List of pausable components that have registered with the GameManager
|
|
private List<IPausable> _pausableComponents = new List<IPausable>();
|
|
private LogVerbosity _settingsLogVerbosity = LogVerbosity.Warning;
|
|
private LogVerbosity _managerLogVerbosity = LogVerbosity.Warning;
|
|
|
|
// Events for pause state changes
|
|
public event Action OnGamePaused;
|
|
public event Action OnGameResumed;
|
|
|
|
// ManagedBehaviour configuration
|
|
public override int ManagedAwakePriority => 10; // Core infrastructure - runs early
|
|
|
|
private new void Awake()
|
|
{
|
|
base.Awake(); // CRITICAL: Register with LifecycleManager!
|
|
|
|
// Set instance immediately so it's available before OnManagedAwake() is called
|
|
_instance = this;
|
|
|
|
// Create settings providers - must happen in Awake so other managers can access settings in their ManagedAwake
|
|
SettingsProvider.Instance.gameObject.name = "Settings Provider";
|
|
DeveloperSettingsProvider.Instance.gameObject.name = "Developer Settings Provider";
|
|
|
|
// Load all settings synchronously - critical infrastructure for other managers
|
|
InitializeSettings();
|
|
InitializeDeveloperSettings();
|
|
|
|
// Load verbosity settings early
|
|
_settingsLogVerbosity = DeveloperSettingsProvider.Instance.GetSettings<DebugSettings>().settingsLogVerbosity;
|
|
_managerLogVerbosity = DeveloperSettingsProvider.Instance.GetSettings<DebugSettings>().gameManagerLogVerbosity;
|
|
}
|
|
|
|
protected override void OnManagedAwake()
|
|
{
|
|
// Settings are already initialized in Awake()
|
|
// This is available for future initialization that depends on other managers
|
|
}
|
|
|
|
/// <summary>
|
|
/// Register a component as pausable, so it receives pause/resume notifications
|
|
/// </summary>
|
|
/// <param name="component">The pausable component to register</param>
|
|
public void RegisterPausableComponent(IPausable component)
|
|
{
|
|
if (component != null && !_pausableComponents.Contains(component))
|
|
{
|
|
_pausableComponents.Add(component);
|
|
|
|
// If the game is already paused, pause the component immediately
|
|
if (IsPaused)
|
|
{
|
|
component.Pause();
|
|
}
|
|
|
|
LogDebugMessage($"Registered pausable component: {(component as MonoBehaviour)?.name ?? "Unknown"}");
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Unregister a pausable component
|
|
/// </summary>
|
|
/// <param name="component">The pausable component to unregister</param>
|
|
public void UnregisterPausableComponent(IPausable component)
|
|
{
|
|
if (component != null && _pausableComponents.Contains(component))
|
|
{
|
|
_pausableComponents.Remove(component);
|
|
LogDebugMessage($"Unregistered pausable component: {(component as MonoBehaviour)?.name ?? "Unknown"}");
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Request a pause. Multiple systems can request pause; the game only resumes when all requests are released.
|
|
/// </summary>
|
|
/// <param name="requester">Optional object requesting the pause (for logging)</param>
|
|
public void RequestPause(object requester = null)
|
|
{
|
|
_pauseCount++;
|
|
if (_pauseCount == 1)
|
|
{
|
|
ApplyPause(true);
|
|
}
|
|
|
|
LogDebugMessage($"Pause requested by {requester?.ToString() ?? "Unknown"}. pauseCount = {_pauseCount}");
|
|
}
|
|
|
|
/// <summary>
|
|
/// Release a previously requested pause. If this brings the pause count to zero the game resumes.
|
|
/// </summary>
|
|
/// <param name="requester">Optional object releasing the pause (for logging)</param>
|
|
public void ReleasePause(object requester = null)
|
|
{
|
|
_pauseCount = Mathf.Max(0, _pauseCount - 1);
|
|
if (_pauseCount == 0)
|
|
{
|
|
ApplyPause(false);
|
|
}
|
|
|
|
LogDebugMessage($"Pause released by {requester?.ToString() ?? "Unknown"}. pauseCount = {_pauseCount}");
|
|
}
|
|
|
|
/// <summary>
|
|
/// Apply pause/resume state to registered components and global systems.
|
|
/// </summary>
|
|
/// <param name="shouldPause">True to pause; false to resume</param>
|
|
private void ApplyPause(bool shouldPause)
|
|
{
|
|
// Only affect timescale if debug setting allows it
|
|
var debugSettings = GetDeveloperSettings<DebugSettings>();
|
|
if (debugSettings != null && debugSettings.PauseTimeOnPauseGame)
|
|
{
|
|
Time.timeScale = shouldPause ? 0f : 1f;
|
|
}
|
|
|
|
// Notify registered components
|
|
foreach (var component in _pausableComponents)
|
|
{
|
|
if (shouldPause)
|
|
component.Pause();
|
|
else
|
|
component.DoResume();
|
|
}
|
|
|
|
// Fire events
|
|
if (shouldPause)
|
|
{
|
|
// TODO: Stop input here?
|
|
InputManager.Instance.SetInputMode(InputMode.UI);
|
|
OnGamePaused?.Invoke();
|
|
}
|
|
else
|
|
{
|
|
// TODO: Release input here?
|
|
InputManager.Instance.SetInputMode(InputMode.GameAndUI);
|
|
OnGameResumed?.Invoke();
|
|
}
|
|
|
|
LogDebugMessage($"Game {(shouldPause ? "paused" : "resumed")}. Paused {_pausableComponents.Count} components.");
|
|
}
|
|
|
|
private void InitializeSettings()
|
|
{
|
|
LogDebugMessage("Starting settings initialization...", "SettingsInitialization", _settingsLogVerbosity);
|
|
|
|
// Load settings synchronously
|
|
var playerSettings = SettingsProvider.Instance.LoadSettingsSynchronous<PlayerFollowerSettings>();
|
|
var interactionSettings = SettingsProvider.Instance.LoadSettingsSynchronous<InteractionSettings>();
|
|
var minigameSettings = SettingsProvider.Instance.LoadSettingsSynchronous<DivingMinigameSettings>();
|
|
|
|
// Register settings with service locator
|
|
if (playerSettings != null)
|
|
{
|
|
ServiceLocator.Register<IPlayerFollowerSettings>(playerSettings);
|
|
LogDebugMessage("PlayerFollowerSettings registered successfully", "SettingsInitialization", _settingsLogVerbosity);
|
|
}
|
|
else
|
|
{
|
|
Debug.LogError("Failed to load PlayerFollowerSettings");
|
|
}
|
|
|
|
if (interactionSettings != null)
|
|
{
|
|
ServiceLocator.Register<IInteractionSettings>(interactionSettings);
|
|
LogDebugMessage("InteractionSettings registered successfully", "SettingsInitialization", _settingsLogVerbosity);
|
|
}
|
|
else
|
|
{
|
|
Debug.LogError("Failed to load InteractionSettings");
|
|
}
|
|
|
|
if (minigameSettings != null)
|
|
{
|
|
ServiceLocator.Register<IDivingMinigameSettings>(minigameSettings);
|
|
LogDebugMessage("MinigameSettings registered successfully", "SettingsInitialization", _settingsLogVerbosity);
|
|
}
|
|
else
|
|
{
|
|
Debug.LogError("Failed to load MinigameSettings");
|
|
}
|
|
|
|
// Log success
|
|
_settingsLoaded = playerSettings != null && interactionSettings != null && minigameSettings != null;
|
|
if (_settingsLoaded)
|
|
{
|
|
LogDebugMessage("All settings loaded and registered with ServiceLocator", "SettingsInitialization", _settingsLogVerbosity);
|
|
}
|
|
else
|
|
{
|
|
Logging.Warning("Some settings failed to load - check that all settings assets exist and are marked as Addressables");
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Check for and initialize developer settings.
|
|
/// </summary>
|
|
private void InitializeDeveloperSettings()
|
|
{
|
|
LogDebugMessage("Starting developer settings initialization...", "SettingsInitialization", _settingsLogVerbosity);
|
|
|
|
// Load developer settings
|
|
var divingDevSettings = DeveloperSettingsProvider.Instance.GetSettings<DivingDeveloperSettings>();
|
|
var debugSettings = DeveloperSettingsProvider.Instance.GetSettings<DebugSettings>();
|
|
|
|
_developerSettingsLoaded = divingDevSettings != null && debugSettings != null;
|
|
|
|
if (_developerSettingsLoaded)
|
|
{
|
|
LogDebugMessage("All developer settings loaded successfully", "SettingsInitialization", _settingsLogVerbosity);
|
|
}
|
|
else
|
|
{
|
|
Logging.Warning("Some developer settings failed to load");
|
|
}
|
|
}
|
|
|
|
|
|
// Helper method to get settings
|
|
private T GetSettings<T>() where T : class
|
|
{
|
|
return ServiceLocator.Get<T>();
|
|
}
|
|
|
|
/// <summary>
|
|
/// Returns the entire settings object of specified type.
|
|
/// </summary>
|
|
/// <typeparam name="T">Type of settings to retrieve</typeparam>
|
|
/// <returns>The settings object or null if not found</returns>
|
|
public static T GetSettingsObject<T>() where T : class
|
|
{
|
|
return Instance?.GetSettings<T>();
|
|
}
|
|
|
|
/// <summary>
|
|
/// Returns the developer settings object of specified type.
|
|
/// </summary>
|
|
/// <typeparam name="T">Type of developer settings to retrieve</typeparam>
|
|
/// <returns>The developer settings object or null if not found</returns>
|
|
public static T GetDeveloperSettings<T>() where T : BaseDeveloperSettings
|
|
{
|
|
return DeveloperSettingsProvider.Instance?.GetSettings<T>();
|
|
}
|
|
|
|
private void LogDebugMessage(string message, string prefix = "GameManager", LogVerbosity verbosity = LogVerbosity.None)
|
|
{
|
|
if (verbosity == LogVerbosity.None)
|
|
{
|
|
verbosity = _managerLogVerbosity;
|
|
}
|
|
|
|
if ( verbosity <= LogVerbosity.Debug)
|
|
{
|
|
Logging.Debug($"[{prefix}] {message}");
|
|
}
|
|
}
|
|
|
|
// LEFTOVER LEGACY SETTINGS
|
|
public float PlayerStopDistance => GetSettings<IInteractionSettings>()?.PlayerStopDistance ?? 6.0f;
|
|
public float PlayerStopDistanceDirectInteraction => GetSettings<IInteractionSettings>()?.PlayerStopDistanceDirectInteraction ?? 2.0f;
|
|
public float DefaultPuzzlePromptRange => GetSettings<IInteractionSettings>()?.DefaultPuzzlePromptRange ?? 3.0f;
|
|
}
|
|
}
|