Understanding Component Initialization in Unity

Do you know the order of methods called on the beginning of object life-cycle? Start, Awake, OnEnable, which one is first or second?

When you create the first script in Unity, the first method that you will see is Start(), which is actually not the first method called in the script.

Then which one is first?

In programming, there is a thing called constructor – a method that constructs an object and initializes its values. In the Unity environment, we are not using constructs, but often we still need a place to initialize some values or get references to other components. We can do it in Awake() method as it is the first method called when component is added to GameObject. Awake() method is called only once!

Next on our list is OnEnable() method. As name suggests, this method is called when component is becoming enabled, which imply that it can be called multiple times by Unity. Keep in mind that it will be called after Awake() but before our next method.

The last method on our list here is famous Start() method! It is called on the first frame that object is active. This method is called after all Awake() and all OnEnable() methods, and just before all Update methods that I wrote in another post[link]. Again, Start() is called only once!

When to use each of them?

In Awake() you should put initialization of variables and gathering of the references to other components. Don’t put any other logic there!

OnEnable() is a place where you should put things that will start or be initialize only when component will be become enabled. These could be starting animations, attaching to events or enabling AI.

You can treat Start() in a very similar way like OnEnable() but you have to keep in mind that it will be called only once! For that reason, it isn’t a place to start animations or AI. It might be a great place to start you scene logic like SceneController or GameController which you won’t deactivate.

Exercise for you

Create simple script with Awake(), OnEnable() and Start() methods with simple Debug.Log() with method name in it and attach it to a GameObject. With that, try to deactivate GameObject and component to see which method is called when.

Let me know what you found out in the comment section below! ?

After that, you can continue reading about differences in Updates in Unity. ?‍?

And if you want to get notified on future content, sign up for the newsletter!

And I hope to see you next time! ?

0 0 votes
Article Rating
Notify of
Inline Feedbacks
View all comments
Would love your thoughts, please comment.x