Allows you to initialize an Editor class when Unity loads, and when your scripts are recompiled.
Static constructors with this attribute are called when scripts in the project are recompiled, also known as a Domain Reload). This happens when:
Avoid asset operations such as asset loading in InitializeOnLoad
methods. InitializeOnLoad
methods are called before asset import completes, which means asset loading from this context can fail, resulting in a null object. To do initialization after a ___domain reload that requires asset operations, use the AssetPostprocessor.OnPostprocessAllAssets callback. This callback supports all asset operations and has a parameter that signals if there was a ___domain reload.
Additional resources: InitializeOnLoadMethodAttribute.
// The following code example defines a small custom class decorated with `[InitializeOnLoad]` // and assigns a member method to the `EditorApplication.update` delegate so that it runs and begins // printing to the console on Editor launch.
using UnityEditor; using UnityEngine;
// InitializeOnLoad ensures this code runs on Editor launch [InitializeOnLoad] class MyClass { // Define a static constructor in which we assign the custom Update method to the delegate static MyClass () { EditorApplication.update += Update; }
// Define a method with the required signature that performs work we want to do on launch static void Update () { Debug.Log("Updating"); } }