I see that we can initialize Variable in Awake()
or Start()
and Awake()
will be called before Start()
.
When should we initialize in Awake
and Start
to have the best performance?
I see that we can initialize Variable in Awake()
or Start()
and Awake()
will be called before Start()
.
When should we initialize in Awake
and Start
to have the best performance?
There's not much difference in the performance. But I can tell you a difference between them.
Take a simple example. Say if you want to print "HELLO" in console even if you have not activated the script in inspector, using Awake() function, you can print it in the console. But if you had written the same thing in Start() function and the script wasn't activated, you don't get any output in the console. That's the difference.
Codes in Start() function get executed only if the script is activated while, codes in Awake() function get executed even if the script is not activated. Try it !
Awake is the equivalent of the ctor. It is called when a MonoBehaviour is created, before any other method.
Start is run the first time the MonoBehaviour is activated. This can be right after Awake or long after. This allows to perform actions that are related to the current state of the app or objects.
For instance, you create an enemy, in Awake, you place everything that is basic initialisation. Then, the enemy is deactivated at the end of Awake. Later on, the enemy is about to be activated but you want to make it red if player is having some specific weapon, then you do it in Start.
OnEnable is similar to Start but happens on every SetActive(true) and on start if enabled. This can be a candidate for your enemy willing to change color over the level based on the player magna for instance.
Usually Awake() is used to initialize if certain values or script are dependent on each other and would cause errors if one of them is initialized too late (awake runs before the game starts). Awake is also called only once for every script instance.
Let me quote the Documentation:
and about Start():
Where the last part makes one big difference
To get to you question:
If the script is NOT enabled at the beginning of your game, and you don't need the variables to be initialized, start would be saving performance as awake()would be called regardless...
every variable would be initialized at the very beginning. At least that's the logical assumption I make.
This topic is well described in the official docmentation (
Awake
andStart
).This section describes why you might need two functions:
The difference between
Awake
andStart
is thatStart
is called only when a script is enabled.These two functions are called before the first
Update
method and there is no performance difference between them. I would say thatAwake
is used to initialize all objects (like a constructor), andStart
is used to link the objects or do something before a game starts.