> ## Documentation Index
> Fetch the complete documentation index at: https://docs-unity.molca.id/llms.txt
> Use this file to discover all available pages before exploring further.

# Runtime subsystem

> RuntimeSubsystem lifecycle, InitializationPriority, and prefab placement.

**File:** `Packages/com.molca.core/Runtime/RuntimeSubsystem.cs`\
**Base for:** `ModalManager`, `ScenarioSessionManager`, `VRFadeManager`, `GameManager`, `TourSubsystem`, etc.

## When to use

Subclass `RuntimeSubsystem` when you need a **cross-scene service** that:

* Must **initialize before** gameplay code runs (controlled by `InitializationPriority`).
* Should be **registered in the DI container** automatically for `[Inject]` and `GetService<T>` resolution.
* Needs **lifecycle hooks** (initialize → activate → deactivate → shutdown) tied to `RuntimeManager`.

For components that don't need cross-scene persistence, use a regular `MonoBehaviour` with `[Inject]` instead.

## Lifecycle

1. **`Initialize(Action<IRuntimeSubsystem> finishCallback)`** — must invoke the callback when finished.
2. **`Activate()`** / **`Deactivate()`** — default toggles `isActive`.
3. **`Shutdown()`** — default calls `Deactivate()`.

## RuntimeMode

Serialized flags can restrict a subsystem to **Editor** and/or **Player** so tooling components do not run in builds.

## InitializationPriority

`RuntimeManager` sorts subsystems in **descending** order: **higher numeric `InitializationPriority` runs first**.

## Placement

Add each subsystem once as an **enabled** child component on the [RuntimeManager](/core/runtime-manager) prefab. Duplicate component types are detected and duplicates removed with a warning.

## Using from code

```csharp theme={null}
using System;
using UnityEngine;
using Molca;

public class MyTelemetrySubsystem : RuntimeSubsystem
{
    public override void Initialize(Action<IRuntimeSubsystem> finishCallback)
    {
        // Register providers, start sockets, etc.
        Activate();
        finishCallback?.Invoke(this);
    }

    public override void Shutdown()
    {
        // Tear down before base / RuntimeManager clears services
        base.Shutdown();
    }
}
```

Attach this **once** on the RuntimeManager prefab and set **InitializationPriority** so it runs before/after dependents.

## API Reference

| Method                   | Signature                                                            | Description                                                                                                                                                      |
| ------------------------ | -------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `Initialize`             | `abstract void Initialize(Action<IRuntimeSubsystem> finishCallback)` | Called by RuntimeManager during bootstrap. Must invoke `finishCallback` when initialization is complete. RuntimeManager waits up to 20 seconds for the callback. |
| `Shutdown`               | `virtual void Shutdown()`                                            | Called when RuntimeManager is destroyed or application quits. Default implementation calls `Deactivate()`. Override to clean up resources before base shutdown.  |
| `Activate`               | `virtual void Activate()`                                            | Enables the subsystem. Default implementation sets `isActive = true`. Called after successful initialization.                                                    |
| `Deactivate`             | `virtual void Deactivate()`                                          | Disables the subsystem. Default implementation sets `isActive = false`. Called during shutdown or when subsystem needs to pause.                                 |
| `Teardown`               | `virtual void Teardown()`                                            | Releases resources and unregisters listeners. Called by `Shutdown()`. Override instead of `Shutdown()` when cleanup is all that is needed.                       |
| `InitializeAsync`        | `virtual Awaitable InitializeAsync(CancellationToken ct)`            | Async initialization alternative — used by subsystems that need async patterns. Cancellation token tied to RuntimeManager shutdown.                              |
| `InitializationPriority` | `int InitializationPriority { get; }`                                | Read-only. Determines initialization order. Higher values initialize first (descending sort). Set in Inspector.                                                  |
| `Mode`                   | `RuntimeMode Mode { get; }`                                          | Read-only. Flags controlling whether subsystem runs in Editor and/or Player builds (`RuntimeMode.Editor`, `RuntimeMode.Runtime`, or both). Set in Inspector.     |
| `isActive`               | `protected bool isActive`                                            | Field. Current activation state. Set by `Activate()` and `Deactivate()`. Check before performing subsystem operations.                                           |
| `ShutdownToken`          | `CancellationToken ShutdownToken { get; }`                           | Lifetime token. Cancelled before `Teardown()` runs. Key background loops on this token so shutdown unwinds cleanly.                                              |

## Troubleshooting

* **Subsystem never initializes:** ensure `finishCallback` is invoked — `RuntimeManager` awaits it with a 20-second timeout.
* **Subsystem runs in builds but shouldn't:** set `RuntimeMode` to **Editor** on the component to exclude it from player builds.
* **`GetSubsystem<T>()` returns null:** the subsystem must be an **enabled** child of the RuntimeManager prefab (or registered via `RuntimeManager.RegisterSubsystem`).

## Unity Editor

<Frame caption="RuntimeManager prefab — child RuntimeSubsystem components and their priorities">
  <img src="https://mintcdn.com/ptmolcateknologinusantara/jWDWJqZnZidoWqQK/images/features/core/runtime-subsystems-on-prefab.png?fit=max&auto=format&n=jWDWJqZnZidoWqQK&q=85&s=990c466745b9896c498813d41401f50b" alt="Runtime Subsystems On Prefab" width="884" height="383" data-path="images/features/core/runtime-subsystems-on-prefab.png" />
</Frame>
