Unity Engine - Event Functions

The Unity Engine provides a set of Event Functions which can be used to create custom behavior in any custom class that inherits from MonoBehaviour. When creating a custom script, MonoDevelop pre-populates our starter code by including basic code for Start() and Update() functions, but it's important to note that there are other event functions, such as events generated by user-events or by collisions detected by the Physics Engine that can also be used in scripts.

Execution Order

The order of execution of these events is specified by the Unity Engine and illustrated in the image below. The image below shows the main event functions that we can use in our custom scripts. There are more event functions than those shown in the image below, but these are the most common ones use in custom scripts.The Unity Documentation - Event Execution Order provides more details about execution order and includes documentation for additional event functions.

The majority of our custom game logic will likely be contained in the Update() function which is called once per frame. We'll use FixedUpdate() when we want to use the Unity Physics Engine to realistic movement of gameObjects.

To optimize event-driven games, it's better to have gameObjects create an event-chain of custom events, rather than to have all gameObject code executed in the Update( ) loop,

Frame-based execution-logic of Event-Functions in a Scene

Assume that the UnityEngine has a list of all GameObjects within a scene, which might similar to the code below: List< GameObject > sceneGameObjects

  1. Each time Unity processes frame (loop) of code for the scene, Unity executes each Event Function for every active gameObject in the list of gameObjects for the Scene. Any code within an Event Function is repeatedly executed in this manner.

  2. When a scene is first loaded or started, Unity executes Awake( ) for every active gameObject in the scene.

  3. Next, Unity executes Start( ) for every active gameObject in a scene.

  4. For any gameObjects created after the initial scene load, Awake( ) and Start ( ) are executed when the gameObject is instantiated.

Summary of Event-Function Execution Logic

  • Awake( ) - Use to initialize gameObjects that other GameObjects must access when they are initialized. (Managers, Singletons, etc)

  • Start( ) - Use to initialize all gameObjects, other than gameObjects that were initialized in Awake.

  • FixedUpdate( ) - Exectued each frame: use for gameObects that will have movement, it is exectued at constant time intervals to give smooth animation.

  • Update( ) - Executed each frame: use for standard gameObject processing, including checking for User Input events

Last updated