Loading lessons...
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:
- 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.
- Physics Step (fixed interval, runs 0 or more times per frame)
FixedUpdate(): Timed physics calculations.- Physics simulation resolves internal collision matrices.
OnCollisionEnter/Stay/Exit()andOnTriggerEnter/Stay/Exit()run.
- 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.
- 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
Awakeruns first on load;Startruns before the firstUpdateonly if enabled.- Physics runs in
FixedUpdate; camera tracking goes inLateUpdate. - Enforce script execution order using
[DefaultExecutionOrder].