docs
Systems
Execution
CoroutineSystem
Architecture and Design

Architecture

Design patterns used

  • Lazy singleton. CoroutineHost stores its instance in a private static field, _instance. The Instance property creates the host the first time it is read and returns the cached instance afterward. The XML documentation describes the class as a singleton with one instance per application session.
  • Unity adapter. The XML documentation describes CoroutineHost as a Unity-side adapter that runs coroutines on behalf of non-MonoBehaviour services. The class is a MonoBehaviour only because Unity requires that for StartCoroutine.

How the system connects to other systems

This system doesn't depend on any other Saffron Library system. Its only external contract is with Unity:

  • StartCoroutine runs the supplied routine on the host GameObject.
  • DontDestroyOnLoad keeps the host GameObject alive across scene loads.
  • AddComponent attaches the CoroutineHost component when the instance is created.
  • DisallowMultipleComponent on the class stops Unity from attaching more than one CoroutineHost to the same GameObject.

Key concepts and terminology

  • Routine. An IEnumerator passed to Run. Unity steps through it as a coroutine.
  • Host. The CoroutineHost GameObject and component. It is created by code, not placed in a scene.
  • Instance. The static reference returned by CoroutineHost.Instance.

Creation and lifecycle flow

  1. Code reads CoroutineHost.Instance.
  2. If _instance is null, CreateInstance runs. It creates a GameObject named [CoroutineHost], calls DontDestroyOnLoad on it, and adds a CoroutineHost component.
  3. Unity calls Awake on the new component. Awake checks for an existing instance. If one exists and is a different object, it destroys the new GameObject and returns. Otherwise it sets _instance to this component and calls DontDestroyOnLoad.
  4. The caller invokes Run(routine).
  5. If routine is null, Run returns without doing anything. Otherwise it calls StartCoroutine(routine).

Notes on the public surface

  • The source defines no method for stopping a routine that was started with Run. Run does not return the started Coroutine, so callers cannot stop it through this class.
  • The source has no events or data flow beyond the coroutine itself.