Question by
Zuburuburu · May 12, 2017 at 06:38 AM ·
c#collisiongameobjectparentingcomponents
How to get parent with component on collision?
I have a game object (A) with several child objects (Ab, Ad), which is also child of another game object (B).
Any of those can get collision (A, Ab, Ad), but I need only to get parent's (game object A) component.
For example, I need to get component "HealthStorage" from game object A but the collision was detected on game object's child Ab.
I would use following function on collided object:
void OnCollisionEnter(Collision collision)
{
HealthStorage temp = collision.transform.parent.gameObject.GetComponent<HealthStorage>();
if (temp != null)
{
...do things
}
}
It seems to be working correctly even If collision has happened on game object A (not its children), i.e. not trying to take its parent (game object B).
How correct is this method and is there a better way to do it?
Comment