Autorun a script on Unity start

Unity - Manual: Running Editor Script Code on Launch (unity3d.com)
启动时运行 Editor 脚本代码 - Unity 手册
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):-

using UnityEngine;
using UnityEditor;

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

A static constructor is always guaranteed to be called before any static function or instance of the class is used, but the InitializeOnLoad attribute ensures that it is called as the editor launches.

An example of how this technique can be used is in setting up a regular callback in the editor (its “frame update”, as it were). The EditorApplication class has a delegate called update which is called many times a second while the editor is running. To have this delegate enabled as the project launches, you could use code like the following:-

using UnityEditor;
using UnityEngine;

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

    static void Update ()
    {
        Debug.Log("Updating");
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 英文文档,一开始我也是抗拒的,边翻译边看,也就花费了1个小时基本就阅读过了,我的英文基础其实很差。附上链接:链接:...
    lonecolonel阅读 13,388评论 3 1
  • 简介 Unity可寻址资源系统 可寻址资源系统提供了一种简单的方法通过“地址”加载资源。简化资源包的创建和部署的管...
    hh5460阅读 13,103评论 2 10
  • This article is a record of my journey to learn Game Deve...
    蔡子聪阅读 9,332评论 0 9
  • 2D 刚体 2D 刚体组件将对象置于物理引擎的控制之下。标准刚体[http://docs.unity3d.com/...
    老叫鸭阅读 10,102评论 0 0
  • Getting Started Use the Current Stable Version (7.1) Buil...
    Leonzai阅读 5,952评论 0 3