- Home /
Need to get parent Object after collision
I've got same troubles with getting parent Object. My object Monster has a MonsterBody Component. After collision with MonsterBody I need to let my Monster know, that he's been attacked. I've made some research, but it didn't work anyway. I guess, I don't get how parents really works. Here's the code:
if (collider.tag == "MonsterBody") collider.GetComponent(),MonsterBody,.transform.parent.gameObject.GetComponent,Monster,().GetHit(BaseDamage*DamageMOD);
I'll glad if you could help me. I'm not really interested in Scripting GetHit() in my MonsterBody, except is the only way.
EDIT: I used "," instead of "<>", cause it seems not working here.
Answer by Jeff-Kesselman · May 15, 2014 at 06:08 PM
Okay, well, to start with.... collider.tag is always going to be the tag of the object this script is on. So it will always be true or false.
Thats because "MonoBehaviour.collider" is a short cut for for "MonoBheaviour.gameobject.collider"
I strongly suspect thats not what you want.
Similarly 'collider.GetComponent().transform.parent" is going to be the same as "transform.parent" or again, the parent of the transform of the game object this script is on.
To get the object collided with, and its parent object, you need to do something like this:
void OnCollisionEnter(Collision collision){
GameObject other = collision.gameObject;
GameObject otherParent = other.transform.parent.gameObject;
}
Ok, big thx man, I solved the problem ! :)
I now understand, that I was trying to get parent from part of gameObject, not just gameObject. Here's the solution(and reason why I was using "tag" ;))
Collider2D[] colliders = Physics2D.OverlapCircleAll(transform.position, 1);
foreach (Collider2D collider in colliders){
if (collider.tag == "EnemyBody"){
GameObject body = collider.gameObject;
GameObject bodyParent = body.transform.parent.gameObject;
bodyParent.GetComponent<Enemy>().GetHit(BaseDamage*Damage$$anonymous$$OD);
}
}
Glad it helped.
In general its not a good idea to redefine variables that already exist in the environment like "collider". You can do it, and it will work, but it makes the code harder to figure out when you look at it later and thus is not great practice.
Your answer
Follow this Question
Related Questions
Collision problem 0 Answers
2D box colliders not touching but are colliding, how to fix? 0 Answers
Weapon System with collide detection (Helps with script pls)!!! 0 Answers
Collision vs trigger 1 Answer
Modular Room System Similar to Mega Man 0 Answers