Architecture
Design patterns used
- Lazy singleton.
CoroutineHoststores its instance in a private static field,_instance. TheInstanceproperty 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
CoroutineHostas a Unity-side adapter that runs coroutines on behalf of non-MonoBehaviour services. The class is aMonoBehaviouronly because Unity requires that forStartCoroutine.
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:
StartCoroutineruns the supplied routine on the host GameObject.DontDestroyOnLoadkeeps the host GameObject alive across scene loads.AddComponentattaches theCoroutineHostcomponent when the instance is created.DisallowMultipleComponenton the class stops Unity from attaching more than oneCoroutineHostto the same GameObject.
Key concepts and terminology
- Routine. An
IEnumeratorpassed toRun. Unity steps through it as a coroutine. - Host. The
CoroutineHostGameObject and component. It is created by code, not placed in a scene. - Instance. The static reference returned by
CoroutineHost.Instance.
Creation and lifecycle flow
- Code reads
CoroutineHost.Instance. - If
_instanceis null,CreateInstanceruns. It creates a GameObject named[CoroutineHost], callsDontDestroyOnLoadon it, and adds aCoroutineHostcomponent. - Unity calls
Awakeon the new component.Awakechecks for an existing instance. If one exists and is a different object, it destroys the new GameObject and returns. Otherwise it sets_instanceto this component and callsDontDestroyOnLoad. - The caller invokes
Run(routine). - If
routineis null,Runreturns without doing anything. Otherwise it callsStartCoroutine(routine).
Notes on the public surface
- The source defines no method for stopping a routine that was started with
Run.Rundoes not return the startedCoroutine, so callers cannot stop it through this class. - The source has no events or data flow beyond the coroutine itself.