- Home /
detect which child Colliders is touched by other object.
I have a gameObject which have several child and each child have it own collider. How i can know which child collider is touched by other gameObject?
I have get an bad infor from searching in google, all the child collider will belong to parent, it will only return parent name.
Is there have anyway to get the child name when the child collider is touched?
thanks you in advice.
Answer by Chris D · Jul 21, 2011 at 06:14 PM
Using OnCollisionEnter should get you the name of the collider currently being hit. For example, attaching the following to each of the children you want to monitor:
function OnCollisionEnter(){
print(gameObject + " has been hit");
should print the name of the child it's attached to to the console.
oh no! i have 60++ children. This is the only way i can try?
No, this doesn't work because only the top-level parent will have a rigidbody, and so only that parent will get OnCollisionEnter messages (from it's own colliders or it's children's colliders). It would report the same gameObject regardless of which child was hit.
Answer by GregoryFenn · Aug 27, 2019 at 09:19 AM
I was searching for ages for a solution and this is it. For anyone interested, here is a sample message for OnCollisionEnter which helps explain the process.
void OnCollisionEnter(Collision collision)
{
//My character is a parent player with two children, each of the children
//has a collider on. One child is tagged "Player_Head", the other is
//tagged "Player_Jacket" (you could also use cp.thisCollider.gameObject.name).
//As far as I know, collision.contacts is the only place where "thisCollider"
//can be found.
ContactPoint cp = collision.contacts[0];
if (cp.thisCollider.gameObject.tag == "Player_Jacket")
{
print("Jacket hit");
}
}
[Solution derived from @SpaceManDan's observation in a comment here: https://answers.unity.com/questions/762004/how-do-you-detect-which-child-collider-was-hit.html ]