Loading lessons...
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 itsUpdate,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:
- Go to Edit -> Project Settings -> Script Execution Order.
- Click + to add scripts.
- 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
enabledproperty. - Unity runs script lifecycle events in arbitrary order by default.
- Set custom priorities in the Script Execution Order window.
- Use
Awakefor reference binding to avoid race conditions inStart.