- Home /
Problem with OnDestroy
When Child gameobject is destroyed , i add a component to his parent. the code like this:
void OnDestroy()
{
Debug.Log("Destroy");
this.myTransformparent.gameObject.AddComponent<GameOver>();
}
then i attach the script to the child.
play the game.![alt text][1]
nothing to do except to exit the game. ![alt text][2]
there are some error in the follow.
!IsDestroying() UnityEngine.GameObject:AddComponent() PlayerScript:OnDestroy() (at Assets/Scripts/PlayerScript.cs:121) batchDelete.reservedObjectCount >= batchDelete.objectCount.
any one can help me ? [1]: /storage/temp/29552-qq截图20140722170304.png [2]: /storage/temp/29553-qq截图20140722170521.png
try adding the GameOver Script through the parent game object itself.If your parent gameobject is having any sript add this function in the script
//Add this method in parent game object's script Eg: ParentScript.cs
public void AddGameOverScript()
{
gameObject.AddComponent<GameOver>();
}
In child gameObject change the code to this
void OnDestroy()
{
//$$anonymous$$ake the call to parent object to add the component
transform.parent.GetComponent<ParentScript>().AddGameOverScript();
//Log that the object is destroyed
Debug.Log("Child object is destroyed");
}
Still has error。 click the paly button, then stop play. always results OnDestroy Error like above.
Answer by TamaHobbit · Sep 16, 2014 at 01:02 PM
Unity doesn't allow you to add components in OnDestroy, because then when the game is shutting down more components are created. When the parent object is destroyed, its children are destroyed as well, at which point we try to add components to parent, which doesn't give a nullreference, but the object IS already destroyed.
What you should do is call AddGameOver from the parent just after you Destroy the child. That way it will not be called when the game shuts down.