- Home /
OnEnable called by disabled object
I just run into the problem, that it seeems the function OnEnable() is called by not enabled objects what causing my script to crash.
Here is the code that produces the following error:
NullReferenceException: Object reference not set to an instance of an object
Code:
void OnEnable()
{
CalculatePositions();
print("CalculatePositions() by OnEnable: " + transform.parent.parent.name); //ERROR HERE
}
It seems, the error is produced by accessing the name of the parent.parent of the code holding object. The parent.parent exists as you can see in following picture:
But is not active (like the object that produces the error message).
Could it be, that the OnEnable() function is called when instantiate an inactive object, causing this problem? If so, how can I work around that?
Strange. You can check if the parent is active before you use it like this transform.parent.parent.gameObject.activeInHierarchy
it should prevent the null error if it gets called at some odd time. When you create an inactive instance OnEnable should not be called unless if you disable it after you instantiated it.
You should add the CalculatePositions method. The error may not be the printing.
I just deleted the CalculatePositions() for testing, the error is the print line... And that OnEnable() is called by a disabled object.
is your prefab disabled or do you disable it after instantiation. Because OnEnable() never gets called from a disabled or inactive object!!!
The moment a gameobject is instantiated from an "active" prefab, any script with Awake and OnEnable get that called immediately. This means that no code related to parenting has been executed and therefore there's not even a single parent.
You can either block the first OnEnable call from happening with a boolean check called "init" which get's set to true in Start. Then, the second time OnEnable is called it will pass and execute.
The other option is to make sure to disable the prefab or gameobject, whatever you're creating the instantiation of, prior to doing that.
Your answer
