Files
AppleHillsProduction/Assets/Scripts/Sound/AudioManager.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

278 lines
10 KiB
C#

using UnityEngine;
using UnityEngine.Audio;
using AppleHills.Core;
using AppleHills.Core.Interfaces;
using System.Collections.Generic;
using AudioSourceEvents;
using System;
using Core.Lifecycle;
public class AudioManager : ManagedBehaviour, IPausable
{
/// <summary>
/// Play all audio, just music or no audio at all when the game is paused.
/// </summary>
public enum PauseBehavior
{ PlayAllAudio, MusicOnly, NoAudio }
public PauseBehavior currentPauseBehavior;
public AudioMixer audioMixer;
private AudioListener _audioListener;
public AppleAudioSource currentlyPlayingVO;
private static AudioManager _instance;
private GameObject _player;
public List<AppleAudioSource> criticalVOSources;
public List<AppleAudioSource> VOSources;
public List<AppleAudioSource> musicSources;
public List<AppleAudioSource> ambienceSources;
public List<AppleAudioSource> SFXSources;
private IAudioEventSource _eventSource;
private bool wasInterrupted;
/// <summary>
/// Singleton instance of the AudioManager.
/// </summary>
public static AudioManager Instance => _instance;
// ManagedBehaviour configuration
public override int ManagedAwakePriority => 30; // Audio infrastructure
public override bool AutoRegisterPausable => true; // Auto-register as IPausable
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()
{
// Auto-registration with GameManager handled by ManagedBehaviour
}
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
_player = QuickAccess.Instance.PlayerGameObject;
_audioListener = QuickAccess.Instance.MainCamera.GetComponent<AudioListener>();
foreach (AppleAudioSource _audioSource in criticalVOSources)
{
Debug.Log("Found source: " + _audioSource.name);
}
}
public void SetAudioPauseBehavior(PauseBehavior newPauseBehavior)
{
switch (newPauseBehavior)
{
case PauseBehavior.PlayAllAudio:
audioMixer.updateMode = AudioMixerUpdateMode.UnscaledTime;
AudioListener.pause = false;
break;
case PauseBehavior.MusicOnly:
audioMixer.updateMode = AudioMixerUpdateMode.UnscaledTime; break;
//TODO: Pause all audio mixers except music mixer
case PauseBehavior.NoAudio:
audioMixer.updateMode = AudioMixerUpdateMode.Normal;
AudioListener.pause = true;
break;
}
}
public LevelAudioObject GetCurrentLevelAudioObject()
{
Debug.Log("Audio objects: " + FindObjectsByType<LevelAudioObject>(FindObjectsInactive.Include, FindObjectsSortMode.None).Length);
if (FindObjectsByType<LevelAudioObject>(FindObjectsInactive.Include, FindObjectsSortMode.None).Length > 1)
{
Debug.LogWarning("Warning! More than one LevelAudioObject in the level! Using the first one found");
return FindObjectsByType<LevelAudioObject>(FindObjectsInactive.Include, FindObjectsSortMode.None)[0];
}
if (FindObjectsByType<LevelAudioObject>(FindObjectsInactive.Include, FindObjectsSortMode.None).Length == 0)
{
Debug.LogWarning("Error! No LevelAudioObject found, AudioManager might not function properly!");
return null;
}
else
return FindFirstObjectByType<LevelAudioObject>();
}
public void Pause()
{
SetAudioPauseBehavior(PauseBehavior.NoAudio);
}
public void DoResume()
{
SetAudioPauseBehavior(PauseBehavior.PlayAllAudio);
}
public void RegisterNewAudioSource(AppleAudioSource newAudioSource)
{
switch (newAudioSource.audioSourceType)
{
case AppleAudioSource.AudioSourceType.CriticalVO:
criticalVOSources.Add(newAudioSource);
break;
case AppleAudioSource.AudioSourceType.VO:
VOSources.Add(newAudioSource);
break;
case AppleAudioSource.AudioSourceType.SFX:
SFXSources.Add(newAudioSource);
break;
case AppleAudioSource.AudioSourceType.Ambience:
ambienceSources.Add(newAudioSource);
break;
case AppleAudioSource.AudioSourceType.Music:
musicSources.Add(newAudioSource);
break;
}
}
/// <summary>
/// Request playing a VO line. Returns true if whatever is playing is not critical, or weight of requested VO line is lower.
/// </summary>
public bool RequestPlayVO(AppleAudioSource requestedAudioSource)
{
//Debug.Log($"[AUDIOMANAGER] CurrentVO source prio: {currentlyPlayingVO.sourcePriority}, clip prio: {currentlyPlayingVO.clipPriority} requested VO prio: {requestedAudioSource.sourcePriority}, clip prio: {clipPriority}");
// If nothing is playing, let the requested audio source play
if (currentlyPlayingVO == null)
{
SetupNewAudioSource(requestedAudioSource);
Debug.Log($"[AUDIOMANAGER] Playing {currentlyPlayingVO.name} as nothing is currently playing.");
return true;
}
// If the requested audio is not critical, and the currently playing audio is, tell the request to get bent
if (requestedAudioSource.audioSourceType == AppleAudioSource.AudioSourceType.VO && currentlyPlayingVO.audioSourceType == AppleAudioSource.AudioSourceType.CriticalVO)
{
return false;
}
// If the requested audio source is the same, interrupt and trigger it again
if (currentlyPlayingVO == requestedAudioSource)
{
InterruptAudioSource(requestedAudioSource);
SetupNewAudioSource(requestedAudioSource);
Debug.Log($"[AUDIOMANAGER] {currentlyPlayingVO.name} is the same as {requestedAudioSource.name}. Triggering it again.");
return true;
}
// if the currently playing audio source is not critical, interrupt it and play the requested audio source
if (currentlyPlayingVO.audioSourceType != AppleAudioSource.AudioSourceType.CriticalVO)
{
InterruptAudioSource(requestedAudioSource);
SetupNewAudioSource(requestedAudioSource);
Debug.Log($"[AUDIOMANAGER] {currentlyPlayingVO.name} is not critical. Playing {requestedAudioSource.name} instead because it is critical.");
return true;
}
// If the requested audio source has the same priority as currently playing source, check the priority of the requested clip
if (currentlyPlayingVO.audioSourceType == AppleAudioSource.AudioSourceType.CriticalVO && currentlyPlayingVO.sourcePriority == requestedAudioSource.sourcePriority)
{
if (currentlyPlayingVO.clipPriority > requestedAudioSource.clipPriority)
{
InterruptAudioSource(requestedAudioSource);
SetupNewAudioSource(requestedAudioSource);
Debug.Log($"[AUDIOMANAGER] Interrupted {currentlyPlayingVO.name} because it has same priority as {requestedAudioSource.name} but the requested clip has higher priority");
return true;
}
else
{
return false;
}
}
// If the requested audio source has higher priority than the currently playing source, interrupt the current source and let the requested one play
if (currentlyPlayingVO.audioSourceType == AppleAudioSource.AudioSourceType.CriticalVO && currentlyPlayingVO.sourcePriority > requestedAudioSource.sourcePriority)
{
currentlyPlayingVO.InterruptAudio(requestedAudioSource.name);
Debug.Log($"[AUDIOMANAGER] Interrupted {currentlyPlayingVO.name} because {requestedAudioSource.name} has higher priority");
InterruptAudioSource(requestedAudioSource);
SetupNewAudioSource(requestedAudioSource);
return true;
}
// If the requested audio source didn't clear any of the above cases, tell it to get rekt.
else
{
Debug.Log($"[AUDIOMANAGER] {currentlyPlayingVO.name} is still playing. {requestedAudioSource.name} has lower priority");
return false;
}
}
private void OnApplicationQuit()
{
// TODO: Release the handles safely ReleaseAllHandles();
}
private void SetupNewAudioSource(AppleAudioSource audioSource)
{
if (audioSource.audioSource.resource == null)
{
Debug.Log($"[AUDIOMANAGER] Faled to setup {audioSource.name}. Invalid resource");
}
else
{
currentlyPlayingVO = audioSource;
_eventSource = audioSource.audioSource.RequestEventHandlers();
_eventSource.AudioStopped += OnAudioStopped;
_eventSource.AudioStarted += OnAudioStarted;
}
}
private void OnAudioStopped(object sender, EventArgs e)
{
if (wasInterrupted)
{
ResetAudioSource();
}
else
{
currentlyPlayingVO = null;
ResetAudioSource();
}
}
private void OnAudioStarted(object sender, EventArgs e)
{
}
private void ResetAudioSource()
{
_eventSource.AudioStopped -= OnAudioStopped;
_eventSource.AudioStarted -= OnAudioStarted;
wasInterrupted = false;
}
private void InterruptAudioSource(AppleAudioSource newAudioSource)
{
wasInterrupted = true;
//currentlyPlayingVO.InterruptAudio(newAudioSource.name);
InterruptAllVOSources();
ResetAudioSource();
currentlyPlayingVO = newAudioSource;
}
private void InterruptAllVOSources()
{
foreach (AppleAudioSource source in criticalVOSources)
{
source.InterruptAudio("GlobalInterrupt");
}
foreach (AppleAudioSource source in VOSources)
{
source.InterruptAudio("GlobalInterrupt");
}
}
}