Version: 2019.2
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

Note: Some browsers do not support SVG image files. If the image above does not display properly (for example, if you cannot see any text), please try another browser, such as Google Chrome or Mozilla Firefox.

First Scene load

These functions get called when a sceneA Scene contains the environments and menus of your game. Think of each unique Scene file as a unique level. In each Scene, you place your environments, obstacles, and decorations, essentially designing and building your game in pieces. More info
See in Glossary
starts (once for each object in the scene).

  • Awake: This function is always called before any Start functions and also just after a prefabAn asset type that allows you to store a GameObject complete with components and properties. The prefab acts as a template from which you can create new object instances in the scene. More info
    See in Glossary
    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 GameObjectThe fundamental object in Unity scenes, which can represent characters, props, scenery, cameras, waypoints, and more. A GameObject’s functionality is defined by the Components attached to it. More info
    See in Glossary
    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 scriptsA piece of code that allows you to create your own Components, trigger game events, modify Component properties over time and respond to user input in any way you like. More info
See in Glossary
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.

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.

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, cameraA component which creates an image of a particular viewpoint in your scene. The output is either drawn to the screen or captured as a texture. More info
See in Glossary
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.

Animation update loop

These functions and ProfilerA window that helps you to optimize your game. It shows how much time is spent in the various areas of your game. For example, it can report the percentage of time spent rendering, animating or in your game logic. More info
See in Glossary
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 machineThe set of states in an Animator Controller that a character or animated GameObject can be in, along with a set of transitions between those states and a variable to remember the current state. The states available will depend on the type of gameplay, but typical states include things like idling, walking, running and jumping. More info
    See in Glossary
    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 EventsAllows you to add data to an imported clip which determines when certain actions should occur in time with the animation. For example, for an animated character you might want to add events to walk and run cycles to indicate when the footstep sounds should play. More info
    See in Glossary
    :
    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 componentA component on a model that animates that model using the Animation system. The component has a reference to an Animator Controller asset that controls the animation. More info
    See in Glossary
    to modify the Root MotionMotion of character’s root node, whether it’s controlled by the animation itself or externally. More info
    See in Glossary
    .

  • 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 clipAnimation data that can be used for animated characters or simple animations. It is a simple “unit” piece of motion, such as (one specific instance of) “Idle”, “Walk” or “Run”. More info
See in Glossary
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: 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-processingA process that improves product visuals by applying filters and effects before the image appears on screen. You can use post-processing effects to simulate physical camera and film properties, for example Bloom and Depth of Field. More info post processing, postprocessing, postprocess
    See in Glossary
    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 GizmosA graphic overlay associated with a GameObject in a Scene, and displayed in the Scene View. Built-in scene tools such as the move tool are Gizmos, and you can create custom Gizmos using textures or scripting. Some Gizmos are only drawn when the GameObject is selected, while other Gizmos are drawn by the Editor regardless of which GameObjects are selected. More info
    See in Glossary
    in the scene viewAn interactive view into the world you are creating. You use the Scene View to select and position scenery, characters, cameras, lights, and all other types of Game Object. More info
    See in Glossary
    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.
  • OnDisable: This function is called when the behaviour becomes disabled or inactive.

  • 2019–03–18 Page amended
Attributes
Understanding Automatic Memory Management