Lesson 19 +10 XP

Scripting Lifecycle Control

Scripting Lifecycle Control

You can control whether scripts are actively running, and define the order in which scripts are initialized.

Enabling and Disabling Components

Every script component has an enabled boolean property:

  • enabled = true: Unity calls its Update, FixedUpdate, and other cycle methods.
  • enabled = false: Unity stops calling its cycle methods.
public class EnemyAI : MonoBehaviour
{
    void OnPlayerSpotted()
    {
        // Enable pathfinding script
        GetComponent<Pathfinding>().enabled = true;
    }
}

Script Execution Order

By default, Unity initializes scripts in an arbitrary order. If script A depends on variables set up by script B in Start, A might run first and throw a null reference error.

To solve this:

  1. Go to Edit -> Project Settings -> Script Execution Order.
  2. Click + to add scripts.
  3. Assign values to define priority. Scripts with lower values (e.g. -100) run before scripts with default values (0) or positive values (100).

Alternatively, initialize references in Awake instead of Start, since Awake is guaranteed to run on all scripts before any Start method is called.

TL;DR

  • Toggle script execution by setting the enabled property.
  • Unity runs script lifecycle events in arbitrary order by default.
  • Set custom priorities in the Script Execution Order window.
  • Use Awake for reference binding to avoid race conditions in Start.