---
title: "关于脚本的生命周期、函数的执行顺序"
author: "Perrin Yong"
author_profile: https://www.pystone.net/profile/
published_by: "Perrin Yong"
canonical: https://www.pystone.net/notes/unity-script-lifecycle-execution-order/
type: note
content_role: unspecified
visibility: public
id_stability: rename-stable
source_path: "10-计算机、信息技术与工程/05-游戏图形与运行时/Unity/关于脚本的生命周期、函数的执行顺序.md"
content_hash: 3cb1a57ea51e2f92128595bb1c9a7fbb8e4aebf98dd561740a516a1da35baba8
knowledge_version: 224c990773de.5fa8af6e39fa
site_commit: 224c990773de166d23a886306577dd90379529ce
notes_commit: 5fa8af6e39fa3891d1b9b4832bfa6c4e0ecaaf0a
---
# 关于脚本的生命周期、函数的执行顺序

> 创建时间：2020/7/24 16:39

## Editor和Engine脚本的执行顺序

在Editor中，非PlayMode下，编辑器执行函数会在一帧里面跑。
进入PlayMode时，会Reload程序集（Assemblies），Reset脚本（Scripts），没有明确的回调函数可以注册，使Editor脚本中函数可以在刚进入PlayMode的时候调用。

脚本使用`[InitializeOnLoad]`属性，可以使脚本可以在刚进入PlayMode的时候初始化（调用静态构造函数）。而这个初始化的时机处在开始进入PlayMode和真正开始Play之前，此时

  * EditorApplication.isPlaying 为 false

  * EditorApplication.isPlayingOrWillChangePlaymode 为 true

  * Unity已经完成了程序集的Reload和脚本的Reset

在此时实例化物体，Unity会报错：Some objects were not cleaned up when closing the scene. (Did you spawn new GameObjects from OnDestroy?)。
这个时候实例化的物体加不到Hierarchy当中，但是会加载到内存当中，显示在Scene当中，Unity会判断内存当中有一块儿不属于当前场景的Object。 判断的结果类似于内存泄漏。

因此，解决方法是，在Static 实例化方法中，使用`EditorApplication.update += Update`给编辑器程序的Update注册函数，想要执行的逻辑在Update当中执行，也就是在下一帧（完全进入Play Mode）时执行。
静态初始化函数调用后到PlayMode第一次Update的时间段中，bu’y’h

## 例子

```csharp
class Program
{
    static void Main(string[] args)
    {
        dynamic dyn = 1;
        object obj = 1;
        dyn = dyn + 3;
        //obj = obj + 3; 报错

        // Rest the mouse pointer over dyn and obj to see their
        // types at compile time.
        System.Console.WriteLine(dyn.GetType());
        System.Console.WriteLine(obj.GetType());
    }
}

```
