Lesson 104 +10 XP

Event Function Execution Order

Event Function Execution Order

Understanding the precise sequence in which Unity invokes event functions is essential for writing bug-free scripts.

Lifecycle Sequence

Every active script runs these phases in order:

  1. Initialization (first frame only)
  • Awake(): Called when the script instance is loaded, even if the component is disabled. Use for self-initialization.
  • OnEnable(): Called when the component is enabled.
  • Start(): Called before the first frame update, only if the script is enabled. Use for cross-object references.
  1. Physics Step (fixed interval, runs 0 or more times per frame)
  • FixedUpdate(): Timed physics calculations.
  • Physics simulation resolves internal collision matrices.
  • OnCollisionEnter/Stay/Exit() and OnTriggerEnter/Stay/Exit() run.
  1. Input & Game Logic
  • Update(): Called once per frame for general logic, inputs, and timer increments.
  • LateUpdate(): Called once per frame after all Update calls have completed. Ideal for cameras tracking moving targets.
  1. Decommissioning
  • OnDisable(): Called when the script or GameObject becomes disabled.
  • OnDestroy(): Called when the GameObject is permanently removed.

Script Execution Order

By default, Unity executes different scripts in an arbitrary order. To enforce a specific order:

  • Go to Edit > Project Settings > Script Execution Order.
  • Or apply the [DefaultExecutionOrder] attribute to your class:
[DefaultExecutionOrder(-100)] // Runs before default scripts
public class GameManager : MonoBehaviour { }

Coroutine Yield Instructions

Coroutines resume execution at distinct phases of the frame:

  • yield return null: Resumes after all Update functions.
  • yield return new WaitForFixedUpdate(): Resumes after all FixedUpdate functions.
  • yield return new WaitForEndOfFrame(): Resumes after rendering is complete.

TL;DR

  • Awake runs first on load; Start runs before the first Update only if enabled.
  • Physics runs in FixedUpdate; camera tracking goes in LateUpdate.
  • Enforce script execution order using [DefaultExecutionOrder].