# エディター起動時のプロジェクトコードの実行

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

Edit モードのプロジェクトコードの一部を、Unity エディターの起動時にユーザーアクションなしで即座に実行すると便利な場合があります。これは [InitializeOnLoad](/engine/6000.0/script-reference/unity-editor/initialize-on-load-attribute.md) 属性を静的コンストラクターのあるクラスに適用することで実現できます。静的コンストラクターは、クラスと同じ名前の関数で、`static` 宣言され、戻り値の型やパラメーターを持ちません。詳細については、Microsoft C# ドキュメントの [Static constructors](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` 属性によりエディター起動時に呼び出されることが保証されます。この属性を持つ静的コンストラクターは、プロジェクト内のスクリプトが再コンパイルされるときに呼び出されます。これは [ドメインリロード](/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) というデリゲートがあり、これはエディターが実行されている間、1 秒間に何度も呼び出されます。以下のコード例では、`[InitializeOnLoad]` で装飾された小さなカスタムクラスを定義し、メンバーメソッドを `EditorApplication.update` デリゲートに割り当てます。これにより、メソッドが実行され、エディター起動時にコンソールに `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)
* [Domain Reload](/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)
