11-0002 Unity中函數的執行過程

1.腳本生命週期流程圖

在這裏插入圖片描述

2.函數調用流程

2.1 First Scene Load

場景啓動時會對場景中的每個對象執行一遍如下事件函數:

  • 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.

  • Awake:遊戲啓動之前初始化任何變量和遊戲狀態,僅在腳本生命週期中調用一次,不能做協程,Start函數之前以及預製物體實例化後被調用。GameObject之間Awake的調用沒有先後順序規定,因而可以利用Awake建立腳本之間的引用,再使用Start 來回傳遞信息。(對於C#、Boo用戶,當構造時組件序列化狀態沒有定義,就應該使用Awake代替構造函數初始化)。
  • OnEnable:只有GameObject是激活狀態下才被調用,通常發生於MonoBehaviour實例被創建。

2.2 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.

  • Reset:首次將腳本附加到對象以及使用“ Reset”命令時,將調用“Reset”以初始化腳本的屬性。

2.3 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.


  • Start:僅在啓用腳本實例的情況下,在第一幀更新之前調用Start。

對於添加到場景中的對象,將在Update之前在所有腳本上調用Start函數,等等。一般情況下,當在遊戲過程中實例化對象時,不能強制執行此操作。

2.4 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.

  • OnApplicationPause:這在檢測到暫停的幀結束時調用,有效地在正常幀更新之間進行。在調用OnApplicationPause之後,將發出一幀額外的幀,以允許遊戲顯示指示暫停狀態的圖形。

2.5 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 when LateUpdate 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.

當您跟蹤遊戲邏輯和互動,動畫,攝像機位置等時,可以使用一些不同的事件。常見的模式是在Update函數中執行大多數任務,但是您還可以使用其他功能。

  • FixedUpdate: 與Update相比,FixedUpdate通常被更頻繁地調用。如果幀速率低,則可以每幀多次調用它;如果幀速率高,則可以在幀之間根本不調用它。所有物理計算和更新都在FixedUpdate之後立即進行。在FixedUpdate中應用運動計算時,無需將值乘以Time.deltaTime。這是因爲在可靠的計時器上調用了FixedUpdate,而與幀速率無關。
  • Update: 每幀調用一次更新。它是幀更新的主要功能。
  • LateUpdate: 更新完成後,每幀調用一次LateUpdate。LateUpdate開始時,Update中執行的所有計算都將完成。LateUpdate的常見用法是後續的第三人稱相機。如果使角色移動並在Update內部旋轉,則可以在LateUpdate中執行所有攝像機的移動和旋轉計算。這將確保角色在攝像機跟蹤其位置之前已完全移動。

2.6 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.

當Unity評估動畫系統時,將調用些功能和Profiler標記。

  • OnStateMachineEnter: 在狀態機更新步驟中,當控制器的狀態機進行流經Entry狀態的轉換時,將在第一個更新幀上調用此回調。它不要求過渡到StateMachine子狀態。
    僅當動畫圖中存在控制器組件(例如AnimatorController或AnimatorOverrideController或AnimatorControllerPlayable)時,才發生此回調。
    Note: 將此回調添加到StateMachineBehaviour組件將禁用多線程狀態機評估。
  • OnStateMachineExit: 在狀態機更新步驟中,當控制器的狀態機進行流經退出狀態的轉換時,將在最後一個更新幀上調用此回調。它不要求過渡到StateMachine子狀態。
    僅當動畫圖中存在控制器組件(例如AnimatorController或AnimatorOverrideController或AnimatorControllerPlayable)時,才發生此回調。
    Note: 將此回調添加到StateMachineBehaviour組件將禁用多線程狀態機評估。
  • Fire Animation Events: 從上次更新時間到當前更新時間之間採樣的所有剪輯中調用所有動畫事件。
  • StateMachineBehaviour (OnStateEnter/OnStateUpdate/OnStateExit): 一層最多可以具有3個活動狀態:當前狀態,中斷狀態和下一個狀態。使用StateMachineBehaviour組件爲每個活動狀態調用此函數,該組件定義OnStateEnter,OnStateUpdate或OnStateExit回調。
    首先針對當前狀態,隨後的中斷狀態以及最後的下一個狀態調用該函數。
    僅當動畫圖中存在控制器組件(例如AnimatorController或AnimatorOverrideController或AnimatorControllerPlayable)時,才發生此步驟。
  • OnAnimatorMove: 每個更新幀,每個Animator組件都會調用一次,以修改Root Motion。
  • StateMachineBehaviour(OnStateMove): 使用定義該回調的StateMachineBehaviour在每個活動狀態上調用此方法。
  • OnAnimatorIK: 設置動畫IK。啓用IK傳遞的每個Animator Controller層都將調用一次。
    僅當您使用人形裝備時,此事件纔會執行。
  • StateMachineBehaviour(OnStateIK): 使用StateMachineBehaviour組件在每個活動狀態上調用該組件,該組件在啓用IK傳遞的層上定義此回調。
  • WriteProperties: 將所有其他動畫屬性從主線程寫入場景。

2.7 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.

腳本生命週期流程圖中顯示的某些動畫函數不是您可以調用的事件函數;它們是事件函數。它們是Unity處理動畫時調用的內部函數。

這些功能具有Profiler標記,因此您可以使用Profiler來查看Unity在框架中何時調用它們。知道Unity何時調用這些函數可以幫助您準確地瞭解所調用的Event函數何時執行。

例如,假設您在FireAnimationEvents回調中調用Animator.Play()。如果您知道僅在執行“狀態機更新”和“過程圖”功能後才觸發FireAnimationEvents回調,則可以預期動畫剪輯將在下一幀播放,而不是立即播放。

  • State Machine Update: 在執行順序的這一步,將評估所有狀態機。僅當動畫圖中存在控制器組件(例如AnimatorController或AnimatorOverrideController或AnimatorControllerPlayable)時,才發生此步驟。
    Note: 狀態機評估通常是多線程的,但是添加某些回調(例如OnStateMachineEnter和OnStateMachineExit)會禁用多線程。有關詳細信息,請參見上面的動畫更新循環。
  • ProcessGraph: 評估所有動畫圖。這包括對所有需要評估的動畫剪輯進行採樣,以及計算Root Motion。
  • ProcessAnimation: 混合動畫圖形的結果。
  • WriteTransforms: 將所有動畫變換從輔助線程寫入場景。
    具有啓用了IK傳遞的多層的Humanoid裝備可以具有多個WriteTransforms傳遞(請參閱腳本生命週期流程圖)。

2.8 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 post-processing of the image, see Post-processing Effects.
  • 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.

  • OnPreCull: 在相機剔除場景之前調用。剔除確定相機可以看到哪些對象。在淘汰之前調用OnPreCull。
  • OnBecameVisible/OnBecameInvisible: 當對象對任何攝像機可見/不可見時調用。
  • OnWillRenderObject: 如果對象可見,則爲每個攝像機調用一次。
  • OnPreRender: 在照相機開始渲染場景之前調用。
  • OnRenderObject: 在完成所有常規場景渲染之後調用。您可以在此時使用GL類或Graphics.DrawMeshNow繪製自定義幾何。
  • OnPostRender: 在照相機完成場景渲染之後調用。
  • OnRenderImage:在場景渲染完成後調用,以允許對圖像進行後期處理,請參閱後期處理效果。
  • OnGUI: 爲響應GUI事件,每幀多次調用。首先處理Layout和Repaint事件,然後是每個輸入事件的Layout和鍵盤/鼠標事件。
  • OnDrawGizmos: 用於在場景視圖中繪製Gizmos,以實現可視化目的。

2.9 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.

在Update函數返回後,將運行常規協程更新。協程是可以暫停其執行(產量)直到給定的YieldInstruction結束的函數。協程的不同用途:

  • yield: 在下一幀調用所有Update函數之後,協程將繼續。
  • yield WaitForSeconds: 在爲幀調用了所有更新功能之後,在指定的時間延遲後繼續。
  • yield WaitForFixedUpdate: 在所有腳本上調用所有FixedUpdate之後繼續。
  • yield WWW: 在WWW下載完成後繼續。
  • yield StartCoroutine: 鏈接協程,並將等待MyFunc協程首先完成。

2.10 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).

  • OnDestroy: 在對對象存在的最後一幀進行所有幀更新後調用此函數(該對象可能會響應Object.Destroy或在場景關閉時被破壞)。

2.11 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.
  • OnDisable: This function is called when the behaviour becomes disabled or inactive.

這些功能在場景中的所有活動對象上調用:

  • OnApplicationQuit: 在退出應用程序之前,將在所有遊戲對象上調用此函數。在編輯器中,當用戶停止播放模式時將調用它。
  • OnDisable: 當行爲變爲禁用或不活動狀態時,將調用此函數。

3.參考鏈接

Link:Order of Execution for Event Functions

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章