Course contentsShow
← Unity Game Development
Lesson 78 of 8282. Scripting and LifecycleFree lesson

Controlling Execution Order with Script Execution Manager

You will configure the Script Execution Order settings to resolve dependency conflicts when multiple scripts must execute in a specific sequence.

In this lesson, you will learn how to resolve dependency conflicts by forcing specific scripts to run before others using the Script Execution Order settings.

The Lifecycle Dilemma

In Unity, the Awake and Start methods of your scripts run in a random order by default. This creates a problem if Script A needs to initialize data that Script B relies on. If Script B tries to access that data before Script A has finished running its Awake logic, your game will likely throw a NullReferenceException.

Instead of writing complex workarounds, you can tell Unity exactly which script should "go first."

Setting the Execution Order

Unity provides a built-in manager to handle this through the Project Settings:

  1. Go to Edit > Project Settings > Script Execution Order.
  2. Click the + button to add your scripts to the list.
  3. Each script has a number associated with it (the "Default Time").
    • Lower numbers execute earlier.
    • Higher numbers execute later.

For example, if you have a GameManager that initializes global settings and a PlayerSpawner that needs those settings, you would add GameManager to the list and give it an order of -100. Then, add PlayerSpawner and give it an order of 100. Now, even if they are on different objects, Unity guarantees that GameManager initializes first.

A Concrete Example

Imagine this scenario:

// GameManager.cs - Should run first
void Awake() {
    GlobalData.Settings = new Settings();
}

// Player.cs - Needs the settings immediately
void Awake() {
    // If Player runs before GameManager, this will crash!
    ApplySettings(GlobalData.Settings);
}

By assigning GameManager a lower execution order value than Player in the settings menu, you ensure the GlobalData is ready before the Player tries to read it, keeping your startup logic clean and error-free.

Key Takeaway: When scripts depend on each other during initialization, use the Script Execution Order menu to assign lower values to parent or manager scripts, ensuring they finish their setup before dependent scripts begin.