- Home /
Destroy(other.gameObject) isn't destroying parent, only children
I have a game object which has 10 child objects, which are all coins. I set up a killregion on the left of the screen that I want to use to destroy everything that touches it.
Here's what I'm using for the KillRegion:
#pragma strict
function Start ()
{
}
function Update ()
{
}
function OnTriggerEnter (other : Collider)
{
Destroy(other.gameObject);
}
The individual coins are all objects with their own box colliders because I want the player to be able to collect them individually. The parent coin group object only has a transform component. The individual coins are all set to be triggers. I've read the information about Object.Destroy and I can't come up with a solution that destroys the children and the parent. I've also tried making the Kill Region a trigger but that didn't lead me anywhere promising yet. Any insight would be great! Thanks!
Answer by foress89 · Jan 07, 2014 at 05:26 AM
Hello, I was looking for an awnser and came up with something myself, I do not know if it's the best solution but it works.
if(other.transform.parent != null) {
Destroy(other.transform.parent.gameObject);
}
else {
Destroy(other.gameObject);
}
My situation is that I have a box collider around my scene and if any objects gets out it gets destroyed. Now some object that required more than one collider (as childs) where not getting completely destroyed... Code snippet is self explained.
I was having a very similar issue to the original poster, and your solution worked like a charm.
Thank You!
Answer by EliteMossy · Apr 06, 2013 at 12:02 AM
To destroy the parent, you could do
Destroy(other.transform.parent.gameObject);
That seems to be deleting the parent, but I'm randomly getting this error regarding that function:
NullReferenceException UnityEngine.Component.get_gameObject () $$anonymous$$illRegion.OnTriggerEnter (UnityEngine.Collider other) (at Assets/Scripts/$$anonymous$$illRegion.js:16)
I'm guessing because I'm destroying the parent and then the child objects have nothing to reference? Is there a more "right" way of doing this?
I also tried adding a collider to the whole group of coins but then I needed to add a rigid body and set that in motion as well as the child coins and it just got messier and messier. If anyone has any other ideas I'd love to hear them. Thanks!