- Home /
How to destroy a parent object when child object is collided
I am initializing set of birds and hitting with an object and trying to destroy the bird which is being hit, but the bird is destroying in the order of spawning(I have attached a collider to the child object since, the bird was imported from maya). This is the script that i have written to destroy the parent object.
#pragma strict
static var score : int;
static var energy : int;
var foo : GameObject;
var foo1 : GameObject;
function Start () {
}
function Update () {
}
function OnCollisionEnter(col : Collision){
if(col.gameObject.name =="Sphere(Clone)"){
Destroy(col.gameObject);
Destroy(gameObject);
var cube : GameObject=GameObject.Find("cube");
foo = cube.transform.parent.gameObject;
foo1 = foo.transform.parent.gameObject;
Destroy(this.foo1);
//Destroy(transform.parent.gameObject);
//var obj: GameObject = col.collider.gameObject;
//Debug.Log(foo1);
//score += 10;
//energy -= 5;
}
}
Answer by Professor Snake · Feb 20, 2013 at 01:06 PM
You are using GameObject.Find("cube")
which will search the entire scene, and return the first cube that it finds (Which usually is the one that is the higher up in the inspector). Instead, if the cube is a child of the object on the script, you should use transform.Find
with a cube:Transform
, which will only search all the children instead. A much more elegant solution would be to have cube be initialised outside of any function and assign the cube to it via the inspector in the prefab.
Thank you for your advice, as i am new to unity could you please give me a proper code to find the parent object of the collided child object.
col.gameObject.transform.parent should do the trick.