- Home /
OnCollisionEnter(Collision Other) setActive affecting parent
Hey guys and thanks for reading.
I have a whole bunch of objects that are linked up to a parent. Whenever one of my bullets hits any of the children objects, all the the objects are being setActive(false); I only want the object which was collided with to be set active. There are 10 or so objects, so having them not under a parent object isn't really an option. This event does not occur if the objects do not have a parent.
Here is the code (attached to the bullet which hits the objects I want to be setActive(false);
void OnCollisionEnter(Collision other){
if(other.collider.transform.tag == "Cube"){
Debug.Log("DESTROYING CUBE");
other.gameObject.SetActive(false);
Destroy(this.gameObject);
}
}
}
Please format your code, if you don't know how, watch the tutorial video on the right!
Answer by sath · Jan 05, 2014 at 10:02 AM
if bullet hit a child it will destroy only this child but if the bullet hit the parent first then all cubes will be destroyed..
To avoid this set parent's tag with different name ("parentCube"),child tag("cube") and rewrite like
//set parent's health script
//Health damage;
void OnCollisionEnter(Collision other){
if(other.collider.transform.tag == "cube"){
Debug.Log("child hitted");
other.transform.parent=null;
other.gameObject.SetActive(false);
Destroy(gameObject);//destroy bullet
}
if(other.collider.transform.tag == "parentCube"){
Debug.Log("Parent hitted");
//here you can set how bullet is making damage to parent
//If you have a script on parent with health you can say :
//damage = other.transform.GetComponent<Health>();//where Health is the name of script is attached to parent
//damage.health-=10;//health is public int health=100; inside Health script
//But if you decide to Destroy parent without destroying the children
//other.transform.DetachChildren();
//Destroy(other.gameObject);
Destroy(gameObject);//destroy bullet
}
}
Everything is depending from your game logic or what you would like to happen to your parentObject..
Thanks for your input. I understand how that code is meant to work, however it doesn't for my code.
If I remove the parent's rigidbody however, the code works fine. ALTHOUGH I am unable to do this as I need the parent to have a rigidbody.
SO FRUSTRATING :C
Also the parent object is untagged, so that isn't the issue