Unity各个函数的执行顺序

本文详细介绍了Unity中脚本的生命周期,包括从初始化到销毁的各个阶段,并解释了不同事件函数如Start、Update、LateUpdate等的调用顺序及应用场景。

无耻一把,直接把Unity的文档摘过来了,不过感觉很有用,就先收藏了:http://docs.unity3d.com/Manual/ExecutionOrder.html

Execution Order of Event Functions

In Unity scripting, there are a number of event functions that get executed in a predetermined order as a script executes. This execution order is described below:

Editor

  • Reset: Reset is called to initialize the script’s properties when it is first attached to the object and also when the Reset command is used.

First Scene Load

These functions get called when a scene starts (once for each object in the scene).

  • Awake: This function is always called before any Start functions and also just after a prefab is instantiated. (If a GameObject is inactive during start up Awake is not called until it is made active.)
  • OnEnable: (only called if the Object is active): This function is called just after the object is enabled. This happens when a MonoBehaviour instance is created, such as when a level is loaded or a GameObject with the script component is instantiated.
  • OnLevelWasLoaded: This function is executed to inform the game that a new level has been loaded.

Note that for objects added to the scene, the Awake and OnEnable functions for all scripts will be called before Start, Update, etc are called for any of them. Naturally, this cannot be enforced when an object is instantiated during gameplay.

Before the first frame update

  • Start: Start is called before the first frame update only if the script instance is enabled.

For objects added to the scene, the Start function will be called on all scripts before Update, etc are called for any of them. Naturally, this cannot be enforced when an object is instantiated during gameplay.

In between frames

  • OnApplicationPause: This is called at the end of the frame where the pause is detected, effectively between the normal frame updates. One extra frame will be issued after OnApplicationPause is called to allow the game to show graphics that indicate the paused state.

Update Order

When you’re keeping track of game logic and interactions, animations, camera positions, etc., there are a few different events you can use. The common pattern is to perform most tasks inside the Update function, but there are also other functions you can use.

  • FixedUpdate: FixedUpdate is often called more frequently than Update. It can be called multiple times per frame, if the frame rate is low and it may not be called between frames at all if the frame rate is high. All physics calculations and updates occur immediately after FixedUpdate. When applying movement calculations inside FixedUpdate, you do not need to multiply your values by Time.deltaTime. This is because FixedUpdate is called on a reliable timer, independent of the frame rate.

  • Update: Update is called once per frame. It is the main workhorse function for frame updates.

  • LateUpdate: LateUpdate is called once per frame, after Update has finished. Any calculations that are performed in Update will have completed whenLateUpdate begins. A common use for LateUpdate would be a following third-person camera. If you make your character move and turn inside Update, you can perform all camera movement and rotation calculations in LateUpdate. This will ensure that the character has moved completely before the camera tracks its position.

Rendering

  • OnPreCull: Called before the camera culls the scene. Culling determines which objects are visible to the camera. OnPreCull is called just before culling takes place.
  • OnBecameVisible/OnBecameInvisible: Called when an object becomes visible/invisible to any camera.
  • OnWillRenderObject: Called once for each camera if the object is visible.
  • OnPreRender: Called before the camera starts rendering the scene.
  • OnRenderObject: Called after all regular scene rendering is done. You can use GL class or Graphics.DrawMeshNow to draw custom geometry at this point.
  • OnPostRender: Called after a camera finishes rendering the scene.
  • OnRenderImage: Called after scene rendering is complete to allow postprocessing of the image, see ImageEffects.
  • OnGUI: Called multiple times per frame in response to GUI events. The Layout and Repaint events are processed first, followed by a Layout and keyboard/mouse event for each input event.
  • OnDrawGizmos Used for drawing Gizmos in the scene view for visualisation purposes.

Coroutines

Normal coroutine updates are run after the Update function returns. A coroutine is a function that can suspend its execution (yield) until the given YieldInstruction finishes. Different uses of Coroutines:

  • yield The coroutine will continue after all Update functions have been called on the next frame.
  • yield WaitForSeconds Continue after a specified time delay, after all Update functions have been called for the frame
  • yield WaitForFixedUpdate Continue after all FixedUpdate has been called on all scripts
  • yield WWW Continue after a WWW download has completed.
  • yield StartCoroutine Chains the coroutine, and will wait for the MyFunc coroutine to complete first.

When the Object is Destroyed

  • OnDestroy: This function is called after all frame updates for the last frame of the object’s existence (the object might be destroyed in response to Object.Destroy or at the closure of a scene).

When Quitting

These functions get called on all the active objects in your scene:

  • OnApplicationQuit: This function is called on all game objects before the application is quit. In the editor it is called when the user stops playmode. In the web player it is called when the web view is closed.
  • OnDisable: This function is called when the behaviour becomes disabled or inactive.

Script Lifecycle Flowchart

The following diagram summarises the ordering and repetition of event functions during a script’s lifetime.

Unity生命周期各阶段的具体执行顺序如下: ### 初始化阶段 - **Awake**:当一个脚本实例被载入时调用,无论脚本是否启用都会执行。常用于初始化变量或引用其他对象,确保在后续阶段可以使用这些初始化的值。 ```csharp void Awake() { // 初始化操作 } ``` - **OnEnable**:当对象启用并激活状态时调用,在Awake之后执行。可以用于在对象启用时启动一些操作。 ```csharp void OnEnable() { // 对象启用时的操作 } ``` - **Start**:仅在Update函数第一次被调用前调用,在对象的第一帧更新之前执行。常用于在游戏开始时执行一些初始化操作,这些操作可能依赖于其他对象的初始化完成。 ```csharp void Start() { // 游戏开始时的初始化操作 } ``` ### 物理阶段 - **FixedUpdate**:以固定的时间间隔调用,用于处理物理相关的操作,如刚体的移动和受力计算。其调用频率可以在项目设置中调整。 ```csharp void FixedUpdate() { // 物理相关操作 } ``` - **OnTriggerEnter、OnTriggerStay、OnTriggerExit**:当一个Collider进入、停留或离开另一个Collider的触发区域时调用,用于处理触发事件。 ```csharp void OnTriggerEnter(Collider other) { // 触发进入事件处理 } ``` - **OnCollisionEnter、OnCollisionStay、OnCollisionExit**:当一个刚体或碰撞器与另一个刚体或碰撞器发生碰撞开始、持续或结束时调用,用于处理碰撞事件。 ```csharp void OnCollisionEnter(Collision collision) { // 碰撞开始事件处理 } ``` ### 输入处理阶段 - **处理用户输入**:在这个阶段,Unity会处理用户的输入,如键盘、鼠标、触摸等输入事件。 ### 更新阶段 - **Update**:每一帧都会调用,用于处理游戏的逻辑更新,如角色的移动、动画的播放等。 ```csharp void Update() { // 游戏逻辑更新 } ``` - **LateUpdate**:在所有Update函数调用后被调用,常用于相机跟随等操作,确保在角色移动完成后相机再进行跟随。 ```csharp void LateUpdate() { // 相机跟随等操作 } ``` ### 渲染阶段 - **OnRenderObject**:在所有常规场景渲染完成后调用,用于自定义渲染操作。 ```csharp void OnRenderObject() { // 自定义渲染操作 } ``` - **OnGUI**:用于绘制GUI元素,在每帧调用多次,以确保GUI元素能够正确响应输入和更新。 ```csharp void OnGUI() { // 绘制GUI元素 } ``` ### 终止阶段 - **OnDisable**:当对象被禁用时调用,可以用于停止一些正在进行的操作,如取消订阅事件。 ```csharp void OnDisable() { // 对象禁用时的操作 } ``` - **OnDestroy**:当脚本销毁或对象被销毁时调用,用于释放资源和清理操作。 ```csharp void OnDestroy() { // 释放资源和清理操作 } ```
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值