Files
AppleHillsProduction/Assets/Scripts/Cinematics/CinematicsManager.cs
tschesky e27bb7bfb6 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
2025-11-07 15:38:31 +00:00

223 lines
7.8 KiB
C#

using System.Collections.Generic;
using Core;
using Core.Lifecycle;
using UI;
using UnityEngine;
using UnityEngine.AddressableAssets;
using UnityEngine.ResourceManagement.AsyncOperations;
using UnityEngine.Playables;
using UnityEngine.UI;
using UI.Core;
namespace Cinematics
{
/// <summary>
/// Handles loading, playing and unloading cinematics
/// </summary>
public class CinematicsManager : ManagedBehaviour
{
public event System.Action OnCinematicStarted;
public event System.Action OnCinematicStopped;
private static CinematicsManager _instance;
private Image _cinematicSprites;
public GameObject cinematicSpritesGameObject;
private bool _isCinematicPlaying = false;
public bool IsCinematicPlaying => _isCinematicPlaying;
public GameObject cinematicBackground;
public DivingGameOverScreen divingGameOverScreen;
// Dictionary to track addressable handles by PlayableDirector
private Dictionary<PlayableDirector, AsyncOperationHandle<PlayableAsset>> _addressableHandles
= new Dictionary<PlayableDirector, AsyncOperationHandle<PlayableAsset>>();
/// <summary>
/// Singleton instance of the CinematicsManager. No longer creates an instance if one doesn't exist.
/// </summary>
public static CinematicsManager Instance => _instance;
public PlayableDirector playableDirector;
public override int ManagedAwakePriority => 170; // Cinematic systems
private new void Awake()
{
base.Awake(); // CRITICAL: Register with LifecycleManager!
// Set instance immediately so it's available before OnManagedAwake() is called
_instance = this;
}
protected override void OnManagedAwake()
{
Logging.Debug("[CinematicsManager] Initialized");
}
private void OnEnable()
{
// Subscribe to application quit event to ensure cleanup
Application.quitting += OnApplicationQuit;
}
private void OnDisable()
{
// Unsubscribe from application quit event
Application.quitting -= OnApplicationQuit;
// Clean up any remaining addressable handles when disabled
ReleaseAllHandles();
}
private void OnApplicationQuit()
{
ReleaseAllHandles();
}
/// <summary>
/// Initializes required components for the CinematicsManager
/// </summary>
private void InitializeComponents()
{
// Initialize PlayableDirector if not set
if (playableDirector == null)
{
playableDirector = GetComponent<PlayableDirector>();
// If still null, try to add the component
if (playableDirector == null)
{
playableDirector = gameObject.AddComponent<PlayableDirector>();
Debug.Log("[CinematicsManager] Added missing PlayableDirector component");
}
}
// Initialize _cinematicSprites if not set
if (_cinematicSprites == null)
{
// First try to find in children
_cinematicSprites = GetComponentInChildren<Image>(true);
// If still null, create a new UI Image for cinematics
if (_cinematicSprites == null)
{
Debug.LogWarning("[CinematicsManager] No Image found for cinematics display. Cinematics may not display correctly.");
}
}
}
/// <summary>
/// Plays a cinematic from an object reference and returns the PlayableDirector playing the timeline
/// </summary>
public PlayableDirector PlayCinematic(PlayableAsset assetToPlay)
{
// Ensure components are initialized before playing
InitializeComponents();
if (_cinematicSprites != null)
{
_cinematicSprites.enabled = true;
cinematicSpritesGameObject.SetActive(true);
}
playableDirector.stopped += OnPlayableDirectorStopped;
playableDirector.Play(assetToPlay);
Logging.Debug("Playing cinematic " + assetToPlay.name);
_isCinematicPlaying = true;
OnCinematicStarted?.Invoke();
return playableDirector;
}
void OnPlayableDirectorStopped(PlayableDirector director)
{
_cinematicSprites.enabled = false;
cinematicSpritesGameObject.SetActive(false);
Logging.Debug("Cinematic stopped!");
_isCinematicPlaying = false;
OnCinematicStopped?.Invoke();
// Release the addressable handle associated with this director
ReleaseAddressableHandle(director);
ShowCinematicBackground(false);
}
/// <summary>
/// Loads a playable from an asset path and plays it as a cinematic
/// </summary>
public PlayableDirector LoadAndPlayCinematic(string key)
{
// Load the asset via addressables
var handle = Addressables.LoadAssetAsync<PlayableAsset>(key);
var result = handle.WaitForCompletion();
// Store the handle for later release
_addressableHandles[playableDirector] = handle;
Logging.Debug($"[CinematicsManager] Loaded addressable cinematic: {key}");
return PlayCinematic(result);
}
/// <summary>
/// Skips the currently playing cinematic if one is active
/// </summary>
public void SkipCurrentCinematic()
{
if (playableDirector != null && playableDirector.state == PlayState.Playing)
{
Logging.Debug("Skipping current cinematic");
playableDirector.Stop();
}
}
/// <summary>
/// Releases the addressable handle associated with a specific PlayableDirector
/// </summary>
private void ReleaseAddressableHandle(PlayableDirector director)
{
if (_addressableHandles.TryGetValue(director, out var handle))
{
Logging.Debug($"[CinematicsManager] Releasing addressable handle for cinematic");
Addressables.Release(handle);
_addressableHandles.Remove(director);
}
}
/// <summary>
/// Releases all active addressable handles
/// </summary>
private void ReleaseAllHandles()
{
foreach (var handle in _addressableHandles.Values)
{
if (handle.IsValid())
{
Addressables.Release(handle);
}
}
_addressableHandles.Clear();
}
public void ShowCinematicBackground(bool shouldBeActive)
{
cinematicBackground.SetActive(shouldBeActive);
}
public void ShowGameOverScreen()
{
if (divingGameOverScreen != null && UIPageController.Instance != null)
{
UIPageController.Instance.PushPage(divingGameOverScreen);
}
else if (divingGameOverScreen != null)
{
// Fallback if UIPageController is not available
divingGameOverScreen.gameObject.SetActive(true);
Logging.Warning("[CinematicsManager] UIPageController not found, falling back to simple activation.");
}
else
{
Logging.Warning("[CinematicsManager] DivingGameOverScreen reference is not set!");
}
}
}
}