# 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
253 lines
8.3 KiB
C#
253 lines
8.3 KiB
C#
using System;
|
|
using System.Threading.Tasks;
|
|
using AppleHills.Core.Settings;
|
|
using Core;
|
|
using Core.Lifecycle;
|
|
using UnityEngine;
|
|
using UnityEngine.AddressableAssets;
|
|
using UnityEngine.ResourceManagement.AsyncOperations;
|
|
|
|
namespace Bootstrap
|
|
{
|
|
/// <summary>
|
|
/// Entrypoint for the Custom Boot initialisation
|
|
/// </summary>
|
|
public static class CustomBoot
|
|
{
|
|
/// <summary>
|
|
/// Current initialisation status
|
|
/// </summary>
|
|
public static bool Initialised { get; private set; }
|
|
|
|
/// <summary>
|
|
/// Event triggered when boot progress changes
|
|
/// </summary>
|
|
public static event Action<float> OnBootProgressChanged;
|
|
|
|
/// <summary>
|
|
/// Event triggered when boot process completes
|
|
/// </summary>
|
|
public static event Action OnBootCompleted;
|
|
|
|
/// <summary>
|
|
/// Current progress of the boot process (0-1)
|
|
/// </summary>
|
|
public static float CurrentProgress { get; private set; }
|
|
|
|
/// <summary>
|
|
/// Called as soon as the game begins
|
|
/// </summary>
|
|
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSplashScreen)]
|
|
private static void Initialise()
|
|
{
|
|
// Create LifecycleManager FIRST - before any bootstrap logic
|
|
// This ensures it exists when boot completes
|
|
LifecycleManager.CreateInstance();
|
|
|
|
//We should always clean up after Addressables, so let's take care of that immediately
|
|
Application.quitting += ApplicationOnUnloading;
|
|
|
|
PerformInitialisation();
|
|
}
|
|
|
|
/// <summary>
|
|
/// Initialise the bootstrapper
|
|
/// </summary>
|
|
public static void PerformInitialisation()
|
|
{
|
|
//Reset progress
|
|
CurrentProgress = 0f;
|
|
|
|
//In editor, perform initialisation synchronously
|
|
if (Application.isEditor)
|
|
{
|
|
InitialiseBootSettingsSync();
|
|
}
|
|
else
|
|
{
|
|
//In builds, just run things asynchronously, since we can add any checks we need early on
|
|
_ = InitialiseBootSettings();
|
|
}
|
|
}
|
|
|
|
|
|
/// <summary>
|
|
/// Called as the game is quitting, allowing for cleanup
|
|
/// </summary>
|
|
private static void ApplicationOnUnloading()
|
|
{
|
|
Application.quitting -= ApplicationOnUnloading;
|
|
PerformDeInitialisation();
|
|
}
|
|
|
|
/// <summary>
|
|
/// De-Initialise the bootstrapper
|
|
/// </summary>
|
|
public static void PerformDeInitialisation()
|
|
{
|
|
Cleanup(runtimeBootSettingsHandle);
|
|
Cleanup(editorBootSettingsHandle);
|
|
Initialised = false;
|
|
}
|
|
|
|
|
|
/// <summary>
|
|
/// Initialise the boot settings asynchronously
|
|
/// </summary>
|
|
private static async Task InitialiseBootSettings()
|
|
{
|
|
await LoadCustomBootSettings();
|
|
Initialised = true;
|
|
CurrentProgress = 1f;
|
|
OnBootProgressChanged?.Invoke(1f);
|
|
OnBootCompleted?.Invoke();
|
|
|
|
// Notify the LifecycleManager that boot is complete
|
|
if (Application.isPlaying)
|
|
{
|
|
LogDebugMessage("Calling LifecycleManager.OnBootCompletionTriggered()");
|
|
if (LifecycleManager.Instance != null)
|
|
{
|
|
LifecycleManager.Instance.OnBootCompletionTriggered();
|
|
}
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Initialise the boot settings synchronously
|
|
/// </summary>
|
|
private static void InitialiseBootSettingsSync()
|
|
{
|
|
LoadCustomBootSettingsSync();
|
|
Initialised = true;
|
|
CurrentProgress = 1f;
|
|
OnBootProgressChanged?.Invoke(1f);
|
|
OnBootCompleted?.Invoke();
|
|
|
|
// Notify the LifecycleManager that boot is complete
|
|
if (Application.isPlaying)
|
|
{
|
|
LogDebugMessage("Calling LifecycleManager.OnBootCompletionTriggered()");
|
|
if (LifecycleManager.Instance != null)
|
|
{
|
|
LifecycleManager.Instance.OnBootCompletionTriggered();
|
|
}
|
|
}
|
|
}
|
|
|
|
|
|
/// <summary>
|
|
/// Clean up the boot settings
|
|
/// </summary>
|
|
/// <param name="handle"></param>
|
|
private static void Cleanup(AsyncOperationHandle<CustomBootSettings> handle)
|
|
{
|
|
if (handle.IsValid())
|
|
{
|
|
handle.Result.Cleanup();
|
|
Addressables.Release(handle);
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Async handle for the runtime custom boot settings scriptable object
|
|
/// </summary>
|
|
private static AsyncOperationHandle<CustomBootSettings> runtimeBootSettingsHandle;
|
|
|
|
/// <summary>
|
|
/// Async handle for the editor custom boot settings object
|
|
/// </summary>
|
|
private static AsyncOperationHandle<CustomBootSettings> editorBootSettingsHandle;
|
|
|
|
/// <summary>
|
|
/// Runtime addressable key
|
|
/// </summary>
|
|
private static string RuntimeAsset = $"{nameof(CustomBootSettings)}_Runtime";
|
|
|
|
/// <summary>
|
|
/// Editor addressable key
|
|
/// </summary>
|
|
private static string EditorAsset = $"{nameof(CustomBootSettings)}_Editor";
|
|
|
|
/// <summary>
|
|
/// Load the custom boot settings asynchronously and run the initialisation method
|
|
/// </summary>
|
|
private static async Task LoadCustomBootSettings()
|
|
{
|
|
if (Application.isEditor)
|
|
{
|
|
editorBootSettingsHandle = await InitialiseBootSettingsAsset(EditorAsset);
|
|
}
|
|
|
|
runtimeBootSettingsHandle = await InitialiseBootSettingsAsset(RuntimeAsset);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Load the custom boot settings synchronously and run the initialisation method
|
|
/// </summary>
|
|
private static void LoadCustomBootSettingsSync()
|
|
{
|
|
if (Application.isEditor)
|
|
{
|
|
editorBootSettingsHandle = InitialiseBootSettingsAssetSync(EditorAsset);
|
|
}
|
|
|
|
runtimeBootSettingsHandle = InitialiseBootSettingsAssetSync(RuntimeAsset);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Initialise the boot settings asset with the given key
|
|
/// </summary>
|
|
/// <param name="key"></param>
|
|
/// <returns></returns>
|
|
private static async Task<AsyncOperationHandle<CustomBootSettings>> InitialiseBootSettingsAsset(string key)
|
|
{
|
|
var handle = Addressables.LoadAssetAsync<CustomBootSettings>(key);
|
|
await handle.Task;
|
|
switch (handle.Status)
|
|
{
|
|
case AsyncOperationStatus.Failed:
|
|
Debug.LogError(handle.OperationException);
|
|
break;
|
|
case AsyncOperationStatus.Succeeded:
|
|
await handle.Result.Initialise();
|
|
break;
|
|
}
|
|
|
|
return handle;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Initialise the boot settings asset with the given key synchronously
|
|
/// </summary>
|
|
/// <param name="key"></param>
|
|
/// <returns></returns>
|
|
private static AsyncOperationHandle<CustomBootSettings> InitialiseBootSettingsAssetSync(string key)
|
|
{
|
|
var handle = Addressables.LoadAssetAsync<CustomBootSettings>(key);
|
|
var result = handle.WaitForCompletion();
|
|
result.InitialiseSync();
|
|
return handle;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Updates the current progress value and triggers the progress event
|
|
/// </summary>
|
|
/// <param name="progress">Progress value between 0-1</param>
|
|
internal static void UpdateProgress(float progress)
|
|
{
|
|
CurrentProgress = Mathf.Clamp01(progress);
|
|
OnBootProgressChanged?.Invoke(CurrentProgress);
|
|
LogDebugMessage($"Progress: {CurrentProgress:P0}");
|
|
}
|
|
|
|
private static void LogDebugMessage(string message)
|
|
{
|
|
if (DeveloperSettingsProvider.Instance.GetSettings<DebugSettings>().bootstrapLogVerbosity <=
|
|
LogVerbosity.Debug)
|
|
{
|
|
Logging.Debug($"[CustomBoot] {message}");
|
|
}
|
|
}
|
|
}
|
|
} |