Search Issue Tracker

By Design



Found in



Issue ID




[Scripting][Mac] Script throws NullReference errors on OnEnable() though object should be initialized on Awake()



To reproduce:
-Create a new unity project
-Import the attached script or copy from below (Project Window -> Import new asset)
-Create a new game object (GameObject -> Create Empty)
-With the new gameobject selected drag the script from the project window into the inspector
-Press play

Expected result:
No errors in the console

Actual result:
Error in console: "Object reference not set to an instance of an object"

Platforms affected:

Platforms unaffected:

Versions affected:
2017.4.30f1, 2018.4.12f1, 2019.3.0f5, 2019.0f4, 2020.1.0a19

The Script contents:

"using UnityEngine;
using Object = System.Object;

public class ThisShouldntHappen : MonoBehaviour
private Object foo;

private void Awake()
foo = new Object();

private void OnEnable()

  1. Resolution Note:

    The reason that this is happening, is because of the lifecycle of MonoBehaviour with ExecuteInEditMode.
    For EditMode:
    Awake is called when the Scene is active, awake will not be called again, before OnDestroy is called. That happens if unloading the Scene.
    OnEnable is called after a domain reload.

    In this scenario, the reason for the NullReference is that Awake has already been called, then if a domain reload happens "object" will be null because its not serialized. If the field is of a serializable type, and have the serializablefield attribute, it would not give this error.

    Looking trough the documentation, we do not cover this area at all. I have pinged the documentation team so they will pick it up.

Add comment

Log in to post comment

All about bugs

View bugs we have successfully reproduced, and vote for the bugs you want to see fixed most urgently.