UnityException: X is not allowed to be called from a MonoBehaviour constructor
UnityException: X is not allowed to be called from a MonoBehaviour constructor (or instance field initializer), call it in Awake or Start instead.
Unity creates components while loading, sometimes off the main thread, before the engine is ready for API calls. Field initializers and constructors run at that moment, so most Unity APIs refuse to run there.
Read the Console line first
X in the message is the API that was called, such as get_main for Camera.main or get_time for Time.time, and the message ends with the script and GameObject that called it.
Common causes
A field initializer calls a Unity API
Initializers run as part of construction, so they hit the same rule.
ExampleC#private Camera cam = Camera.main; // not allowed private float spawnTime = Time.time; // not allowed private int seed = Random.Range(0, 1000); // not allowedThe class has a constructor
MonoBehaviours and ScriptableObjects should not use constructors for setup at all; Unity may call them more than once, including in the Editor.
The fix
private Camera cam;
private float spawnTime;
void Awake()
{
cam = Camera.main;
spawnTime = Time.time;
}Stop it coming back
Initialize fields with plain values only (numbers, strings, new lists), and do anything that touches the engine in Awake, OnEnable or Start. For ScriptableObjects, use OnEnable.
Questions
- Why do plain values work in initializers but Camera.main does not?
- Values like
5fornew List<int>()do not touch the engine. Camera.main, Time.time, Random.Range and GetComponent ask the engine for something, and it is not ready while the object is being constructed. - Is Awake or Start the right place?
- Use Awake for references the object needs itself, and Start for anything that depends on other objects having finished their own Awake.
- Does this apply to static fields?
- Yes. A static field initialized with a Unity API runs when the class is first loaded, which can be just as early. Initialize it from Awake or with
[RuntimeInitializeOnLoadMethod].
Scripts that avoid it
Related errors
Got a different error? Paste it into the error lookup.