- Home /
How to detect if collision is against child?
I have a parent object and a child object. The parent has a script with OnTriggerEnter and both the parent and child have trigger colliders. If an object enters the child collider, the parent gets the message. Both the parent and child have rigid bodies as well. Is there any way to tell that the child actually fired this message so the parent script knows not to act on messages from the child?
I think children colliders are considered part of their parent. Would it be possible to take the collider from the parent and put it on a child gameobject to make both colliders siblings or do you have some logic that absolutely requires a child/parent relationship?
This way, their OnTriggerEnter()
methods would be called independantly.
Answer by jespercal · May 30, 2017 at 07:41 AM
I'll assume that the parent is already detecting the child and that you just need a way to check if it's the child of the parent or not.
For this I would use:
void OnTriggerEnter(Collider col) {
if( !col.transform.IsChildOf(transform) )
{
// This isn't a child of mine, do something
}
}
Answer by DFT-Games · May 29, 2017 at 11:20 PM
Hi @homer_3 ,
Put your script on the parent object (which must have a rigid body). Unity will notify the parent of all the collision and trigger events, that is by design.
While collisions are easy to detect because they return a collection of contact points, each containing both the objects that collided, for triggers the situation is different, because you only get the other object, so there is no immediate way to know which trigger was hit. The easiest way I can thing of is to use the messages, delegating the other object (which in turn has detected the same event and has our data) to send us a message to let us know which trigger he hit.
I know that is a tad convoluted, but there is no other way.
Your answer
Follow this Question
Related Questions
Unity2D side collision detection 1 Answer
Object Collision PLEASE HELP!!! 1 Answer
Very simple collision death 1 Answer
Best collision detection method? 2 Answers
How do you execute Trigger-collider collision only in one gameobject? 1 Answer