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.
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:
Nota: Algunos navegadores no son compatibles con los archivos de imagen SVG. Si la imagen de arriba no se muestra correctamente (por ejemplo, si no puede ver ningún texto), intente con otro navegador, como Google Chrome o Mozilla Firefox.
Estas funciones son llamadas cuando la escena comienza (una para cada objeto en la escena).
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 you instantiate an object during gameplay.
For objects that are part of a scene asset, the Start function is called on all scripts before Update, etc is called for any of them. Naturally, this cannot be enforced when you instantiate an object during gameplay.
Cuando usted hace seguimiento de la lógica de juego y las interacciones, animaciones, posiciones de cámara, etc., hay unos eventos diferentes que usted puede utilizar. El patrón común es realizar la mayoría de tareas dentro de la función Update , pero también hay otras funciones que usted puede utilizar.
FixedUpdate: FixedUpdate a veces es más llamada que Update. Puede ser llamada varias veces por frame, si la velocidad de frame es baja y puede no ser llamada entre frames en absoluto si la velocidad de frame es alta. Todos los cálculos de física y actualizaciones ocurren inmediatamente después de FixedUpdate. Cuando aplique cálculos de movimiento dentro de FixedUpdate, usted no necesita multiplicar sus valores por Time.deltaTime. Esto se debe a que FixedUpdate en un temporizador fiable, independiente de la velocidad de frames.
Update: Update se llama una vez por frame. Es la función principal para las actualizaciones de frames.
LateUpdate: LateUpdate es llamada una vez por frame, después de que Update haya finalizado. Cualquier cálculo que sea realizado en Update será completado cuando LateUpdate comience. Un uso común para LateUpdate sería una cámara de tercera persona que sigue. Si usted hace que su personaje se mueva y gire, Update, usted puede realizar todos los cálculos de movimientos de cámara y rotación en LateUpdate. Esto asegurara que el personaje haya sido movido completamente antes de que la cámara haga un seguimiento a su posición.
In general, you should not rely on the order in which the same event function is invoked for different GameObjects — except when the order is explicitly documented or settable. (If you need a more fine-grained control of the player loop, you can use the PlayerLoop API.)
You cannot specify the order in which an event function is called for different instances of the same MonoBehaviour subclass. For example, the Update function of one MonoBehaviour might be called before or after the Update function for the same MonoBehaviour on another GameObject — including its own parent or child GameObjects.
You can specify that the event functions of one MonoBehaviour subclass should be invoked before those of a different subclass (using the Script Execution Order panel of the Project Settings window). For example, if you had two scripts, EngineBehaviour and SteeringBehaviour, you could set the Script Execution Order such that EngineBehaviours always updates before SteeringBehaviours.
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.
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.
Actualizaciones normales de Coroutines (corrutinas) son ejecutadas después del return que hace la función Update. Una coroutine es una función que puede suspender su ejecución (yield) hasta que la YieldInstruction finalice. Diferentes usos de Coroutines:
Estas funciones son llamadas en todos los objetos activos en su escena: