Files
AppleHillsProduction/docs/managed_behavior/technical_reference.md
Michal Pikulski dcf8c8bb87 Add documentation
2025-11-11 13:32:02 +01:00

12 KiB

ManagedBehaviour System - Technical Reference

Version: 2.0
Updated: 11.11.2025


Overview

The ManagedBehaviour system provides a deterministic, ordered lifecycle management framework for Unity MonoBehaviours. This document provides complete technical documentation of all classes, methods, and APIs.


Core Classes

ManagedBehaviour (Abstract Base Class)

Namespace: Core.Lifecycle
Inherits: MonoBehaviour
Location: Assets/Scripts/Core/Lifecycle/ManagedBehaviour.csView Source

Abstract base class that all managed components must inherit from. Provides automatic registration with LifecycleManager and ordered lifecycle callbacks.

Lifecycle Hook Methods

Override these internal virtual methods to customize component behavior at different lifecycle stages. Called automatically by LifecycleManager.

Click to see more details
OnManagedAwake()
internal virtual void OnManagedAwake()

Called: During registration (within Unity's Awake phase)
Execution Order: Natural Unity script execution order (not guaranteed between components)
Use For:

  • Setting singleton instances (_instance = this)
  • Early GetComponent calls
  • One-time initialization that doesn't depend on other systems

Timing Guarantees:

  • GameObject and component exist
  • Scene is loaded
  • Other components may not be initialized yet
  • Bootstrap may not be complete
OnManagedStart()
internal virtual void OnManagedStart()

Called: After bootstrap completes (for boot components) or immediately after registration (for late-registered components)
Execution Order: Registration order
Use For:

  • Initialization that depends on other managers
  • Accessing singleton instances safely
  • Setting up cross-system dependencies

Timing Guarantees:

  • All managers are initialized
  • Bootstrap resources are available
  • Safe to access GameManager.Instance, AudioManager.Instance, etc.
OnSceneUnloading()
internal virtual void OnSceneUnloading()

Called: Before scene unload
Execution Order: Registration order
Use For:

  • Scene-specific cleanup
  • Saving temporary scene state

Timing Guarantees:

  • Scene is still loaded
  • Other components in scene still exist
OnSceneReady()
internal virtual void OnSceneReady()

Called: After scene load completes
Execution Order: Registration order
Use For:

  • Scene-specific initialization
  • Finding scene objects
  • Setting up scene-specific state

Timing Guarantees:

  • All scene GameObjects are loaded
  • Batched components have received OnManagedStart()
OnSceneSaveRequested()
internal virtual string OnSceneSaveRequested()

Called: Before scene unload during scene transitions
Returns: Serialized scene-specific data (JSON string), or null if nothing to save
Use For:

  • Level progress
  • Object positions
  • Puzzle states
  • Temporary scene data

⚠️ Important: Must return synchronously.

OnSceneRestoreRequested(string serializedData)
internal virtual void OnSceneRestoreRequested(string serializedData)

Called: After scene load, during OnSceneReady phase
Parameters:

  • serializedData - Previously saved data from OnSceneSaveRequested()

Use For:

  • Restoring level progress
  • Setting object positions
  • Restoring puzzle states

⚠️ Important: Must execute synchronously. Do not use coroutines or async/await.

OnSceneRestoreCompleted()
internal virtual void OnSceneRestoreCompleted()

Called: After all OnSceneRestoreRequested() calls complete
Timing: Always called after scene load, whether save data exists or not
Use For:

  • Post-restore initialization
  • First-time initialization (when no save data exists)
  • Triggering events after state is restored

Common Pattern:

internal override void OnSceneRestoreCompleted()
{
    if (!_hasPlayed) // Check if this is first time
    {
        PlayIntroAudio();
        _hasPlayed = true;
    }
}
OnGlobalSaveRequested()
internal virtual string OnGlobalSaveRequested()

Called: Once before save file is written to disk
Returns: Serialized global persistent data (JSON string), or null
Use For:

  • Player inventory
  • Unlocked features
  • Card collections
  • Persistent progression

Timing: Called once per game save (not per scene transition)

OnGlobalRestoreRequested(string serializedData)
internal virtual void OnGlobalRestoreRequested(string serializedData)

Called: Once on game boot after save file is read
Parameters:

  • serializedData - Previously saved data from OnGlobalSaveRequested()

Use For:

  • Restoring player inventory
  • Restoring unlocked features
  • Restoring persistent progression

Timing: Called once on boot, not during scene transitions

OnGlobalLoadCompleted()
internal virtual void OnGlobalLoadCompleted()

Called: Once on game boot after all global restore operations complete
Use For:

  • Triggering UI updates after load
  • Broadcasting load events
  • Post-load initialization
OnGlobalSaveStarted()
internal virtual void OnGlobalSaveStarted()

Called: Once before save file is written
Use For:

  • Final validation before save
  • Cleanup operations before save
OnManagedDestroy()
internal virtual void OnManagedDestroy()

Called: During OnDestroy, before unregistration
Execution Order: Registration order
Use For:

  • Unsubscribing from events
  • Releasing resources
  • Custom cleanup logic

Note: Most cleanup is automatic (auto-registrations are handled by framework).

Configuration Properties

Virtual properties that control automatic behaviors like pause registration and save system participation.

Click to see more details
AutoRegisterPausable
public virtual bool AutoRegisterPausable => false;

Type: bool
Default: false
Description: If true and component implements IPausable, automatically registers with GameManager.Instance during initialization. Automatic unregistration occurs on destruction.

AutoRegisterForSave
public virtual bool AutoRegisterForSave => false;

Type: bool
Default: false
Description: If true, component participates in the save/load system. Should override OnSceneSaveRequested() and OnSceneRestoreRequested() or global equivalents.

SaveId
public virtual string SaveId { get; }

Type: string
Default: "{SceneName}/{GameObjectName}/{ComponentType}"
Description: Unique identifier for this component in the save system. Cached on first access for performance. Override for singletons (e.g., "PlayerController") or custom IDs.

⚠️ Warning: GameObject name changes at runtime will NOT update the cached SaveId.

Private Lifecycle Methods

Click to see more details
Awake()
private void Awake()

Visibility: private (sealed, cannot be overridden) Called By: Unity Description: Automatically registers component with LifecycleManager. Calls OnManagedAwake() during registration.

⚠️ Important: This method is sealed. Use OnManagedAwake() for early initialization.

OnDestroy()
private void OnDestroy()

Visibility: private (sealed, cannot be overridden) Called By: Unity Description: Calls OnManagedDestroy(), unregisters from LifecycleManager, and handles auto-unregistrations.

⚠️ Important: This method is sealed. Use OnManagedDestroy() for custom cleanup.


LifecycleManager (Singleton Orchestrator)

Namespace: Core.Lifecycle
Inherits: MonoBehaviour
Location: Assets/Scripts/Core/Lifecycle/LifecycleManager.csView Source

Central orchestrator that manages all ManagedBehaviour components and broadcasts lifecycle events.

Static Properties

Instance

Singleton instance. Created automatically by CustomBoot before bootstrap begins.

Public Methods

Core methods for registration, lifecycle broadcasting, and save/restore operations. Most are called automatically by the framework.

Click to see more details
Register(ManagedBehaviour component)
public void Register(ManagedBehaviour component)

Registers a component with the lifecycle system. Called automatically from ManagedBehaviour.Awake().

Unregister(ManagedBehaviour component)
public void Unregister(ManagedBehaviour component)

Unregisters a component. Called automatically from ManagedBehaviour.OnDestroy().

OnBootCompletionTriggered()
public void OnBootCompletionTriggered()

Called by CustomBoot after bootstrap completes. Broadcasts OnManagedStart() to all registered components.

BeginSceneLoad(string sceneName)
public void BeginSceneLoad(string sceneName)

Activates scene loading batching mode. Called by SceneManagerService when loading a scene.

BroadcastSceneReady(string sceneName)
public void BroadcastSceneReady(string sceneName)

Processes batched components and broadcasts OnSceneReady() to all components in the scene. Called by SceneManagerService after scene load.

BroadcastSceneUnloading(string sceneName)
public void BroadcastSceneUnloading(string sceneName)

Broadcasts OnSceneUnloading() to all components in the specified scene. Called by SceneManagerService before scene unload.

BroadcastSceneSaveRequested()
public Dictionary<string, string> BroadcastSceneSaveRequested()

Broadcasts OnSceneSaveRequested() to all components with AutoRegisterForSave == true. Returns dictionary of SaveId → serialized data.

BroadcastSceneRestoreRequested(Dictionary<string, string> saveData)
public void BroadcastSceneRestoreRequested(Dictionary<string, string> saveData)

Distributes save data to components by matching SaveId, then broadcasts OnSceneRestoreCompleted().

BroadcastGlobalSaveRequested()
public Dictionary<string, string> BroadcastGlobalSaveRequested()

Broadcasts OnGlobalSaveRequested() to all components with AutoRegisterForSave == true. Returns dictionary of SaveId → serialized data.

BroadcastGlobalRestoreRequested(Dictionary<string, string> saveData)
public void BroadcastGlobalRestoreRequested(Dictionary<string, string> saveData)

Distributes save data to components by matching SaveId, then broadcasts OnGlobalLoadCompleted().

BroadcastGlobalSaveStarted()
public void BroadcastGlobalSaveStarted()

Broadcasts OnGlobalSaveStarted() to all components with AutoRegisterForSave == true.

LifecyclePhase (Enum)

Namespace: Core.Lifecycle
Location: Assets/Scripts/Core/Lifecycle/LifecycleEnums.csView Source

Defines the different lifecycle phases for documentation and tooling purposes.

public enum LifecyclePhase
{
    ManagedAwake,       // During registration (Awake)
    ManagedStart,       // After bootstrap or late registration
    SceneUnloading,     // Before scene unload
    SceneReady,         // After scene load
    SaveRequested,      // Before scene unload (save)
    RestoreRequested,   // After scene load (restore)
    ManagedDestroy      // During OnDestroy
}