Awake or Start? Pick wrong and you get a null.

When each one runs, and what goes in it.

Awake or Start? Pick wrong and you get a null.

The problem

Null, but only sometimes.

// HUD.csvoid Awake(){    _health = Player.Instance.Health; // NullReferenceException} // Player.csvoid Awake() => Instance = this;

It works or crashes depending on which object Unity happens to wake first.

Why it happens

Every Awake runs before any Start.

When a scene loads, Unity calls Awake on everything first. Only then does it call Start.

1 · Awake
every object, any order
2 · Start
every object, after all Awakes

The fix

Set up yourself, then talk to others.

In Awake, only touch your own object. In Start, every other object is already awake.

Awake→my own setup
Start→talk to others

The fix in code

Move it to Start.

// Player.csvoid Awake() => Instance = this; // HUD.csvoid Start(){    _health = Player.Instance.Health;}

Player sets Instance in Awake. HUD reads it in Start, when it's guaranteed to exist.

The rule

Awake for yourself. Start for others.

Get my components
Awake
Find other objects
Start
Order between objects
not guaranteed