C# Constructor in MonoBehaviour

How is the constructor called in MonoBehaviour?

It seems a constructor is called twice if it’s in a gameobject via MonoBehaviour?

Example:

using UnityEngine;
using System.Collections;

public class Constructors : MonoBehaviour {

public Constructors(){
	print("Constructor");
   }
}

When you press play in the editor,
Console reads:

Constructor
UnityEngine.MonoBehaviour:print(Object)

Constructor

When you press stop in the editor,
Console has an additional extra line reading “Constructor” with these three separate lines:

Constructor
UnityEngine.MonoBehaviour:print(Object)

Constructor

Constructor

As everybody else is saying, don’t use constructors. With the way unity works, you’re supposed to use Awake and Start to handle initialization behavior.

To explain what you are seeing: yes, the constructor is called three times. You’d get the same result if you implemented the ISerializationCallbackReceiver interface, and put a debug in OnBefore/AfterDeserialize. You’d even get the same thing where the first debug would point back to the line of the debug, while the other one would be just the debug text with no extra info.

Now, I think that gives a clue about why you’re recommended to not use constructors. See, serialization of the objects in the scene (and the scripts on them) happens a lot; whenever you save, whenever you press play, a lot of times. Instantiation of new objects, and thus calls to the constructor, probably happens as a part of that process. So if you say create a new gameobject as a part of your constructor, you’d be seeing that gameobject being added to your scene at different points when you didn’t expect the constructor to be called.

Awake and Start, on the other hand, only happens exactly when the application starts playing, and when things are instantiated in play mode. So to prevent stuff from leaking from the serialization process to the scene, avoid constructors.