Attributes
Understanding Automatic Memory Management

Order of Execution for Event Functions

Running a Unity script executes a number of event functions in a predetermined order. This page describes those event functions and explains how they fit into the execution sequence.

Script lifecycle overview

The diagram below summarizes how Unity orders and repeats event functions over a script’s lifetime.

For more information about the various event functions, see the following sections:

Script lifecycle flowchart

注意:有些浏览器不支持 SVG 图像文件。如果以上图像未正确显示(例如,如果看不到任何文字),请尝试其他浏览器,例如 Google ChromeMozilla Firefox

First Scene load

场景开始时将调用以下函数(为场景中的每个对象调用一次)。

  • Awake:始终在任何 Start 函数之前并在实例化预制件之后调用此函数。(如果游戏对象在启动期间处于非活动状态,则在激活之后才会调用 Awake。)
  • OnEnable:(仅在对象处于激活状态时调用)在启用对象后立即调用此函数。在创建 MonoBehaviour 实例时(例如加载关卡或实例化具有脚本组件的游戏对象时)会执行此调用。
  • OnLevelWasLoaded:执行此函数可告知游戏已加载新关卡。

请注意,对于添加到场景中的对象,在为任何对象调用 Start 和 Update 等函数之前,会为_所有_脚本调用 Awake 和 OnEnable 函数。当然,在游戏运行过程中实例化对象时,不能强制执行此调用。

Editor

  • Reset:调用 Reset 可以在脚本首次附加到对象时以及使用 Reset 命令时初始化脚本的属性。

Before the first frame update

  • Start:仅当启用脚本实例后,才会在第一次帧更新之前调用 Start。

对于添加到场景中的对象,在为任何脚本调用 Update 等函数之前,将在所有脚本上调用 Start 函数。当然,在游戏运行过程中实例化对象时,不能强制执行此调用。

In between frames

  • OnApplicationPause:在帧的结尾处调用此函数(在正常帧更新之间有效检测到暂停)。在调用 OnApplicationPause 之后,将发出一个额外帧,从而允许游戏显示图形来指示暂停状态。

Update Order

跟踪游戏逻辑和交互、动画、摄像机位置等的时候,可以使用一些不同事件。常见方案是在 Update 函数中执行大多数任务,但是也可以使用其他函数。

  • FixedUpdate:调用 FixedUpdate 的频度常常超过 Update。如果帧率很低,可以每帧调用该函数多次;如果帧率很高,可能在帧之间完全不调用该函数。在 FixedUpdate 之后将立即进行所有物理计算和更新。在 FixedUpdate 内应用运动计算时,无需将值乘以 Time.deltaTime。这是因为 FixedUpdate 的调用基于可靠的计时器(独立于帧率)。

  • Update:每帧调用一次 Update。这是用于帧更新的主要函数。

  • LateUpdate:每帧调用一次 LateUpdate__(在 Update__ 完成后)。LateUpdate 开始时,在 Update 中执行的所有计算便已完成。LateUpdate 的常见用途是跟随第三人称摄像机。如果在 Update 内让角色移动和转向,可以在 LateUpdate 中执行所有摄像机移动和旋转计算。这样可以确保角色在摄像机跟踪其位置之前已完全移动。

Animation update loop

These functions and Profiler Markers are called when Unity evaluates the Animation system.

  • OnStateMachineEnter: During the State Machine Update step, this callback is called on the first update frame when a controller’s state machine makes a transition that flows through an Entry state. It is not called for a transition to a StateMachine sub-state.

    This callback occurs only if there is a controller component (for example, AnimatorController or AnimatorOverrideController or AnimatorControllerPlayable) in the animation graph.

    Note: Adding this callback to a StateMachineBehaviour component disables multithreaded state machine evaluation.

  • OnStateMachineExit: During the State Machine Update step, this callback is called on the last update frame when a controller’s state machine makes a transition that flows through an Exit state. It is not called for a transition to a StateMachine sub-state.

    This callback occurs only if there is a controller component (for example, AnimatorController or AnimatorOverrideController or AnimatorControllerPlayable) in the animation graph.

    Note: Adding this callback to a StateMachineBehaviour component disables multithreaded state machine evaluation.

  • Fire Animation Events: Calls all animation events from all clips sampled between the time of the last update and the time of the current update.

  • StateMachineBehaviour (OnStateEnter/OnStateUpdate/OnStateExit): A layer can have up to 3 active states: current state, interrupted state, and next state. This function is called for each active state with a StateMachineBehaviour component that defines the OnStateEnter, OnStateUpdate, or OnStateExit callback.

    The function is called for the current state first, then the interrupted state, and finally the next state.

    This step occurs only if there is a controller component (for example, AnimatorController or AnimatorOverrideController or AnimatorControllerPlayable) in the animation graph..

  • OnAnimatorMove: Every update frame, this is called once for each Animator component to modify the Root Motion.

  • StateMachineBehaviour(OnStateMove): This is called on each active state with a StateMachineBehaviour that defines this callback.

  • OnAnimatorIK: Sets up animation IK. This is called once for each Animator Controller layer with IK pass enabled.

    This event executes only if you are using a Humanoid rig.

  • StateMachineBehaviour(OnStateIK): This is called on each active state with a StateMachineBehaviour component that defines this callback on a layer with IK pass enabled.

  • WriteProperties: Writes all other animated properties to the Scene from the main thread.

Useful profile markers

Some of the animation functions shown in the Script Lifecycle Flowchart are not Event functions that you can call; they are internal functions called when Unity processes your animation.

These functions have Profiler Markers, so you can use the Profiler to see when in the frame Unity calls them. Knowing when Unity calls these functions can help you understand exactly when the Event functions you do call are executed.

For example, suppose you call Animator.Play in the FireAnimationEvents callback. If you know that the FireAnimationEvents callback is fired only after the State Machine Update and Process Graph functions execute, you can anticipate that your animation clip will play on the next frame, and not right away.

  • State Machine Update: All state machines are evaluated at this step in the execution sequence. This step occurs only if there is a controller component (for example, AnimatorController or AnimatorOverrideController or AnimatorControllerPlayable) in the animation graph.

    Note: State machine evaluation is normally multithreaded, but adding certain callbacks (for example OnStateMachineEnter and OnStateMachineExit) disables multithreading. See Animation update loop above for details.

  • ProcessGraph: Evaluates all animation graphs. This includes sampling all animation clips that need to be evaluated, and computing Root Motion.

  • ProcessAnimation: Blends the results of the animation graph.

  • WriteTransforms: Writes all animated transforms to the scene from a worker thread.

    A Humanoid rig with multiple layers that have IK pass enabled can have multiple WriteTransforms passes (See the Script Lifecycle Flowchart.

Rendering

  • OnPreCull:在摄像机剔除场景之前调用。剔除操作将确定摄像机可以看到哪些对象。正好在进行剔除之前调用 OnPreCull。
  • OnBecameVisible/OnBecameInvisible:对象变为对任何摄像机可见/不可见时调用。
  • OnWillRenderObject:如果对象可见,则为每个摄像机调用一次
  • OnPreRender:在摄像机开始渲染场景之前调用。
  • OnRenderObject:所有常规场景渲染完成之后调用。此时,可以使用 GL 类或 Graphics.DrawMeshNow 来绘制自定义几何形状。
  • OnPostRender:在摄像机完成场景渲染后调用。
  • OnRenderImage:在场景渲染完成后调用以允许对图像进行后处理,请参阅后期处理效果
  • OnGUI:每帧调用多次以响应 GUI 事件。首先处理布局和重新绘制事件,然后为每个输入事件处理布局和键盘/鼠标事件。
  • OnDrawGizmos 用于在场景视图中绘制辅助图标以实现可视化。

Coroutines

Update 函数返回后将运行正常协程更新。协程是一个可暂停执行 (yield) 直到给定的 YieldInstruction 达到完成状态的函数。 协程的不同用法:

  • yield 在下一帧上调用所有 Update 函数后,协程将继续。
  • yield WaitForSeconds 在为帧调用所有 Update 函数后,在指定的时间延迟后继续协程
  • yield WaitForFixedUpdate 在所有脚本上调用所有 FixedUpdate 后继续协程
  • yield WWW 在 WWW 下载完成后继续。
  • yield StartCoroutine 将协程链接起来,并会等待 MyFunc 协程先完成。

When the Object is destroyed

  • OnDestroy:对象存在的最后一帧完成所有帧更新之后,调用此函数(可能应 Object.Destroy 要求或在场景关闭时销毁该对象)。

When quitting

在场景中的所有活动对象上调用以下函数:

  • OnApplicationQuit:在退出应用程序之前在所有游戏对象上调用此函数。在编辑器中,用户停止播放模式时,调用函数。
  • OnDisable:行为被禁用或处于非活动状态时,调用此函数。

Attributes
Understanding Automatic Memory Management