文档

Unity Engine

Unity Engine

在 Editor 启动时运行项目代码

Run Edit mode code automatically when the Editor launches using the InitializeOnLoad attribute.
阅读时间3 分钟最后更新于 1 个月前

有时,在 Unity Editor 启动时立即运行编辑模式项目代码的某些部分,而无需用户执行任何操作,这可能会很有用。为实现此目的,可将 InitializeOnLoad 属性应用于具有静态构造函数的类。静态构造函数是一个与类同名的函数,声明为
static
,没有返回类型或参数。有关更多信息,请参阅 Microsoft C# 文档中的静态构造函数。
using UnityEngine;using UnityEditor;[InitializeOnLoad]public class Startup { static Startup() { Debug.Log("Up and running"); }}
在使用任何静态函数或类实例之前始终会调用静态构造函数,但
InitializeOnLoad
属性可确保在 Editor 启动时调用该函数。重新编译项目中的脚本时,将调用具有此属性的静态构造函数,也称为域重新加载。发生这种情况时:
  • Unity 首先加载项目。
  • 如果在 Preferences 窗口的 Asset Pipeline 部分中启用了 Auto Refresh,Unity 会检测对脚本的修改。
  • 如果在 Play Mode 配置中启用了 Domain Reload,则进入播放模式。
加载时初始化功能的一个使用示例是设置常规回调,这可被视为编辑器应用程序的某种“帧更新”。EditorApplication 类有一个名为 update 的委托会在 Editor 运行时每秒调用很多次。以下代码示例定义了一个用
[InitializeOnLoad]
装饰的小自定义类,并为
EditorApplication.update
委托分配了一个成员方法,使其在 Editor 启动时运行并开始将
Updating
打印到控制台:
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"); }}

其他资源