Accessing the code lifecycle
Understand how and when the Editor reloads parts of your project code, and how your code can hook into the code lifecycle to perform setup and cleanup at key stages.
Read time 7 minutesLast updated 2 days ago
During the period of its availability, code is loaded, initialized, executed, decommissioned, and unloaded or destroyed. This sequence of stages through which code transitions is referred to as the code lifecycle.
Sometimes it can be necessary to execute code at specific stages of the code lifecycle. For example, to perform appropriate setup or cleanup work at key points prior to or following the loading or unloading of script assemblies, or on transition between Edit mode and Play mode.
Unity enables this by providing public lifecycle APIs that allow your code to receive callbacks at specific points in the code lifecycle.
Lifecycle APIs
A set of public attributes, mostly in the namespace, provides a more coherent alternative to an older set of lifecycle APIs that were a mixture of attributes, events, and interfaces.
Unity.Scripting.LifecycleManagementThe new APIs include callbacks for stages of the code lifecycle that were not previously accessible to user code. While some older APIs are bound to code reload, the new APIs are guaranteed to work with any future scripting runtimes and code reload mechanisms.
The new APIs are also symmetrical. For each callback on loading code or entering a state, there is a corresponding one for unloading code or exiting the state. The new APIs are also available in the Editor and the Player where necessary.
The tables in the following sections list the new lifecycle APIs alongside older APIs with equivalent functionality and timings in the code lifecycle. It's recommended to adopt the newer APIs in new code.
Code reload callbacks
The following APIs allow you to receive callbacks at key stages of the code reload process. The new APIs are in the namespace, which is accessible both in the Editor and in Player builds. The newer APIs offer the following key advantages:
Unity.Scripting.LifecycleManagement- and
[OnCodeDeinitializing]offer direct access to previously inaccessible phases of the code lifecycle. The closest equivalent in the older APIs was to use[OnCodeUnloading]and manually manage subscriptions.AssemblyReloadEvents.beforeAssemblyReload - executes before assets are fully loaded, making it better for resource pre-allocation than its older counterparts
[OnCodeInitializing],[InitializeOnLoad], and[InitializeOnLoadMethod], which execute after.RuntimeInitializeOnLoad
Lifecycle phase | New API | Older API |
|---|---|---|
| Serialization of managed objects during code reload. | | No pre-existing equivalent. |
| Before code is unloaded for a code reload. | | |
After assemblies are loaded and initialized. This happens:
| | No pre-existing equivalent. |
After restoring (deserializing) managed objects following a code reload. At this point:
| | |
For more information and usage examples, refer to the API references for these attributes.
For details of the relative execution order of these callbacks in the context of code reload, refer to Code lifecycle execution order reference.
Play mode and Edit mode transition callbacks
The following APIs allow you to receive callbacks on entry to and exit from Edit mode and on entry to and exit from Play mode. The newer APIs are in the and namespaces respectively. They are two symmetrical attribute pairs that correspond to entry to and exit from Edit mode and entry to and exit from Play mode. They offer two key advantages over the older :
UnityEditor.Scripting.LifecycleManagementUnityEngineEditorApplication.playModeStateChange- As attributes rather than events, they avoid the overhead and risks of subscribing to events, filtering on enum values, and subscription leaks.
- As the entering and exiting Play mode callbacks are in the namespace, you don't have to use preprocessor directives to exclude them from compilation in Player scripts.
UnityEngine
Lifecycle phase | New API | Older API |
|---|---|---|
On initializing or re-initializing Play mode, which happens:
| | |
On shutting down Play mode, which happens:
| | |
On initialization or re-initialization of Edit mode, which happens:
| | |
On shutting down Edit mode, which happens:
| | |
For more information and usage examples, refer to the API references for these attributes.
For an example of using these APIs to reset static state on entering and exiting Play mode, refer to Resetting state from code.
For details of the relative execution order of these callbacks in the context of entering and exiting Play mode, refer to Code and scene reload execution order reference.
Code lifecycle scopes
The lifecycle APIs come in symmetrical pairs, such as and . The interval between the entering callback of a pair and its matching exiting callback is called a code lifecycle scope. While a scope is active, the conditions it represents are true. For example, while the CodeLoaded scope is active, all of your project's code is loaded and safe to discover with reflection or .
[OnCodeLoaded][OnCodeUnloading]TypeCacheThe following table lists the code lifecycle scopes, from outermost to innermost:
Scope | Entering callback | Exiting callback | Active while | Available in |
|---|---|---|---|---|
| AssemblyLoaded | | | The assembly that contains the callback is loaded. Each callback is called only for its own assembly. | Editor and Player |
| CodeLoaded | | | All assemblies are loaded. This scope ends before every code reload and starts again after it. | Editor and Player |
| CodeInitialized | | | Managed objects are restored and usable. | Editor and Player |
| EditMode | | | The Editor is in Edit mode. | Editor only |
| PlayMode | | | The Editor is in Play mode, or a Player is running. | Editor and Player |
Scopes nest inside each other. An inner scope is entered only while all the scopes outside it are active, and it's always exited before any of them. EditMode and PlayMode are both innermost and are never active at the same time. In a Player, there's no code reload, so each scope is entered once at startup and exited once on quit.
The following diagram shows the scopes during an example Editor session in which you start the Editor, enter and exit Play mode, change a script, and quit. The left edge of each bar is the scope's entering callback and the right edge is its exiting callback:
Code lifecycle scopes during an example Editor session
Use scopes in your code
Scopes help you decide which pair of callbacks to use and what you can rely on inside them:
- Clean up in the matching callback: Anything you set up in an entering callback, such as an event subscription, a cache, or a native allocation, release in the exiting callback of the same pair. Unity guarantees that every entering callback is followed by its matching exiting callback before the scope is entered again.
- Choose the scope that matches how long your data must live: For example, reset per-session state in the PlayMode pair, and rebuild caches of types or methods in the CodeLoaded pair, because those caches are invalid after a code reload.
- Rely on outer scopes being active: Inside any callback, every scope outside the current one is active. For example, always runs after your code is loaded and initialized. Similarly, inner scopes always exit first, so
[OnEnteringPlayMode]always runs before[OnExitingEditMode]and[OnCodeDeinitializing].[OnCodeUnloading] - Expect scopes to repeat: In the Editor, CodeLoaded, CodeInitialized, EditMode, and PlayMode can start and end many times in one session. An assembly that stays loaded during a code reload receives only once, but receives a new
[OnAssemblyLoaded]and[OnCodeLoaded]pair for every code reload.[OnCodeUnloading]