Monobehaviours are building blocks of developing games in unity. You can create components and assign them to gameobjects to control their behaviour. You can think of components as scripts derived from monobehaviour base class.
Where objects are instantiated during gameplay, their Awake function is called after the Start functions of Scene objects have already completed. The Start function can be defined as a Coroutine, which allows Start to suspend its execution (yield). Unity does not support constructors. That's why you don't see constructors being used in any class inheriting MonoBehaviour, and I believe any class used by Unity directly in general. $endgroup$ – XenoRo Apr 19 '19 at 0:35. Watch this video in context on Unity Learn:to use Awake and Start, two of Unity's initialisation functions.
Monobehaviours have special methods that are called by the unity engine. Unity documentation says:
- Awake: This function is always called before any Start functions and also just after a prefab is instantiated. (If a GameObject is inactive during start up Awake is not called until it is made active.)
- Start: Start is called before the first frame update only if the script instance is enabled.
- Update: Update is called once per frame. It is the main workhorse function for frame updates.
Awake and Start methods are used to initialize components before they become active in the scene.
Experienced C# developers know that classes have constructors and the constructor is called once for every instance created. We put initialization code (e.g., setting default values) in the constructor and we should avoid adding application logic to constructors.
Since Monobehaviours are classes, they also have constructors. If you do not define one the compiler will generate a default constructor for you. You should avoid using constructors to initialize monobehaviours. Monobehaviours should be initialized with special methods called Awake or Start.
To see in what order the constructor, Awake and Start methods are called, create a test scene and add an empty game object. Attach the below script to the newly created gameobject.
Unity Awakening
Unity Awake Vs Onenable
When you hit play you can see the below lines printed in the console. (The constructor is called twice.)
More interestingly when you hit play again to exit the play mode you can see that the constructor is called again:
Depending on what you do in the constructor you can see unexpected results if you execute code in the constructor.
Another thing to note is that constructors of monobehaviours are not called on the main thread. Change the constructor as below:
Unity Awake
And when you hit play you can see in the console that unity is complaining about using constructors: