Unity script execution order and Start()

DisturbedNeo picture DisturbedNeo · Nov 1, 2016 · Viewed 8.2k times · Source

Unity's documentation has this line:

By default, the Awake, OnEnable and Update functions of different scripts are called in the order the scripts are loaded (which is arbitrary).

So I have two questions here:

  1. What does "Arbitrary" mean in this context? Is it random?
  2. Does this also include Start() alongside Awake(), or does Start() have its own special behaviour that doesn't follow the script execution order, even if that order has been altered in the project settings?

I've wondered for a while how Unity "decides" how it behaves when it runs, especially since it seems like something will work some of the time but the rest of the time it causes a crash or something with little to no explanation, but the documentation doesn't really mention it much and I can't seem to find much info elsewhere.

Answer

Programmer picture Programmer · Nov 1, 2016

That statement is somehow confusing.

Awake, OnEnable and Update will always be called in order.

1.What does "Arbitrary" mean in this context? Is it random?

Yes, its random. Although, it is not talking about the Awake, OnEnable and Update functions. It is talking about scripts. The scripts are randomly chosen to execute.

2.Does this also include Start() alongside Awake(), or does Start() have its own special behaviour that doesn't follow the script execution order, even if that order has been altered in the project settings?

Answer #1 should also answer question #2. This does not affect the callback functions such as Start() Awake(), or OnEnable().

I've wondered for a while how Unity "decides" how it behaves when it runs, especially since it seems like something will work some of the time but the rest of the time it causes a crash or something with little to no explanation

Yes, this is true. This has happened to me in the past too. This is more prone to happen when you have large project with many scripts. The scripts are called randomly. Sometimes, you can get null exception error because GetComponent failed to work. This is why the Script Execution Order Settings is made so that you can always set the order in which your scripts execute.

What I do to fix problems like this is to perform GetComponent in a coroutine function. After that, I check if it is null. If it is null, wait for one frame then try GetComponent again.

Again, this applies to the order in which your scripts are executed not order in which callback functions are invoked/called.