# 在 Editor 启动时运行项目代码

> Run Edit mode code automatically when the Editor launches using the InitializeOnLoad attribute.

有时，在 Unity Editor 启动时立即运行编辑模式项目代码的某些部分，而无需用户执行任何操作，这可能会很有用。为实现此目的，可将 [InitializeOnLoad](/engine/6000.0/script-reference/unity-editor/initialize-on-load-attribute.md) 属性应用于具有静态构造函数的类。静态构造函数是一个与类同名的函数，声明为 `static`，没有返回类型或参数。有关更多信息，请参阅 Microsoft C# 文档中的[静态构造函数](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/static-constructors)。

```lang-csharp
using UnityEngine;
using UnityEditor;

[InitializeOnLoad]
public class Startup {
    static Startup()
    {
        Debug.Log("Up and running");
    }
}
```

在使用任何静态函数或类实例之前始终会调用静态构造函数，但 `InitializeOnLoad` 属性可确保在 Editor 启动时调用该函数。重新编译项目中的脚本时，将调用具有此属性的静态构造函数，也称为[域重新加载](/engine/6000.0/manual/scripting/compilation-and-code-reload/code-reloading-editor/configurable-enter-play-mode/domain-reloading.md)。发生这种情况时：

* Unity 首先加载项目。
* 如果在 [Preferences 窗口](/engine/6000.0/manual/unity-editor/editor-features/preferences.md)的 Asset Pipeline 部分中启用了 **Auto Refresh**，Unity 会检测对脚本的修改。
* 如果在 [Play Mode 配置](/engine/6000.0/manual/scripting/compilation-and-code-reload/code-reloading-editor/configurable-enter-play-mode.md)中启用了 Domain Reload，则进入播放模式。

加载时初始化功能的一个使用示例是设置常规回调，这可被视为编辑器应用程序的某种“帧更新”。[EditorApplication](/engine/6000.0/script-reference/unity-editor/editor-application.md) 类有一个名为 [update](/engine/6000.0/script-reference/unity-editor/editor-application/update.md) 的委托会在 Editor 运行时每秒调用很多次。以下代码示例定义了一个用 `[InitializeOnLoad]` 装饰的小自定义类，并为 `EditorApplication.update` 委托分配了一个成员方法，使其在 Editor 启动时运行并开始将 `Updating` 打印到控制台：

```lang-csharp
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");
    }
}
```

## 其他资源

* [可配置的进入运行模式](/engine/6000.0/manual/scripting/compilation-and-code-reload/code-reloading-editor/configurable-enter-play-mode.md)
* [域重新加载](/engine/6000.0/manual/scripting/compilation-and-code-reload/code-reloading-editor/configurable-enter-play-mode/domain-reloading.md)
* [InitializeOnLoadAttribute](/engine/6000.0/script-reference/unity-editor/initialize-on-load-attribute.md)
