Search Issue Tracker
By Design
Votes
0
Found in
2017.4.30f1
2019.3.0f4
Issue ID
1214025
Regression
Yes
[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:
Mac
Platforms unaffected:
Windows
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;
[ExecuteInEditMode]
public class ThisShouldntHappen : MonoBehaviour
{
private Object foo;
private void Awake()
{
foo = new Object();
}
private void OnEnable()
{
Debug.Log(foo.ToString());
}
}"
Add comment
All about bugs
View bugs we have successfully reproduced, and vote for the bugs you want to see fixed most urgently.
Latest issues
- Unable to change the Shadow Map resolution for lights via Inspector when 'preserveCachedShadow' is enabled
- Adaptive Probe Volumes are not loaded when Adaptive Light Probes are exported via Asset Bundles and opened on another project
- Sprites are not present in Player when built
- TrackPropertyValue callback stops being called when modifying PropertyField
- [Android] [Particle System] "ParticleSystem.GeometryJob" sometimes takes up to ~20 ms in the worker thread when initializing 5 Particle Systems
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.