- Home /
Why is destroying a GameObject also destroying all GameObjects created by said object via Instantiate?
I'm trying to have a GameObject clone itself, and after a certain number of reproductions, the object dies via Destroy(this.gameObject)
. However, when I do this, it destroys itself as well as ALL instantiated object. How do I have the Destroy method only apply to the object it is invoked on, and not any of its instantiated clones?
I an destroying the object with Destroy(this.gameObject);
, and cloning it with the folloowing code:
GameObject offspringObject = Instantiate<GameObject>(this.gameObject, this.rigidBody.transform);
I've also tried using a prefab in place of this.gameObject
for cloning, but the children are still all destroyed.
try removing the parent reference in the instantiated objects. when the parent dies, the children will too.
It seems that your hierarchy for your gameobject isn't correct. If you want to destroy only the gameobject and not the children, why are the children under that gameobject. Typically if you destroy a parent you should destroy the children as they are associated. That or you have choosen the wrong gameobject to destroy. Take a look at this:
https://docs.unity3d.com/ScriptReference/Transform.SetParent.html
PS. It might be helpful to show a picture of your hierarchy and tell us what is being destroyed and what you want to keep so we can help. Or at least a text version of your gameobject hierarchy
Answer by tanoshimi · Jan 09, 2017 at 08:24 PM
Change
GameObject offspringObject = Instantiate<GameObject>(this.gameObject, this.rigidBody.transform);
to
GameObject offspringObject = Instantiate<GameObject>(this.gameObject);
to prevent parenting rhe clones to tbis object.