首页 > 代码库 > 监听Unity3d启动事件 - InitializeOnLoad

监听Unity3d启动事件 - InitializeOnLoad

设想这样的一个场景:

你写了一个Unity3d插件,放到Unity Asset Store上面出售,某一天你更新了一个版本,如何让用户知道你更新了呢?

结合目前所有软件的更新检测方案,在Unity中可用的就是监听Unity3d的启动事件检测更新。


好。


我们项目中用到了AstarPath寻路,每次打开工程,都会在Console中打印出检测更新的日志,点进去看到他的源代码如下:

	[InitializeOnLoad]
	/** Checking for updates on startup */
	public static class UpdateChecker {
	    static UpdateChecker()
	    {
			AstarPathEditor.CheckForUpdates ();
	    }
	}

我们看到第一行

[InitializeOnLoad]

来看下Unity的解释:

Running Editor Script Code on Launch

Sometimes, it is useful to be able to run some editor script code in a project as soon as Unity launches without requiring action from the user.You can do this by applying the InitializeOnLoad attribute to a class which has a static constructor. A static constructor is a function with the same name as the class, declared static and without a return type or parameters (see here for more information):-

开始就说的很清楚了,在启动Unity的时候运行编辑器脚本。

需要静态的构造函数!


下面是官方的例子:

using UnityEngine;
using UnityEditor;

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

下面是一个监听Update的例子:

using UnityEditor;
using UnityEngine;

[InitializeOnLoad]
class MyClass
{
    static MyClass ()
    {
        EditorApplication.update += Update;
    }

    static void Update ()
    {
        Debug.Log("Updating");
    }
}

监听Unity3d启动事件 - InitializeOnLoad