0
\$\begingroup\$

I have parent object with 3 children. Each children has one collider (BoxColliders actually) marked as triggers each one.

I want to know in a OnTriggerEnter on the parent side which collider was hit.

Similar to this question: How can I determine which Trigger is hit? But for 3D Colliders (not 2d). As you can see in the accepted answer they used Collider2D.IsTouching but it doesn't seem to exist any analogue method for a 3D Collider

If is not possible, what other solutions are there? What would be the recommended way? I would like to avoid the overhead from methods like CompareTag and SendMessage if possible.

http://answers.unity.com/answers/1206114/view.html

\$\endgroup\$
2
\$\begingroup\$

You can give the parent class a public method that takes two arguments, a Collider and some form of identification for which child was hit (e.g. a Transform or Vector3 or int id, depending on what layout the children are in). Then, in each child object, give them a script like

using UnityEngine;

public class ChildCollider : MonoBehaviour {
    void OnTriggerEnter(Collider other) {
        transform.parent.gameObject.GetComponent<ParentScript>.OnChildTriggerEntered(other, transform.position);
    }
}

and in the ParentScript script

public void OnChildTriggerEntered(Collider other, Vector3 childPosition) {
    //Do stuff
}
\$\endgroup\$
  • \$\begingroup\$ The approach is right, but you cannot call custom script methods on GameObjects. ChildCollider should store a reference to the instance of the script which method you call. \$\endgroup\$ – trollingchar Jun 7 at 8:50
  • \$\begingroup\$ Thanks, edited. This is what I get for not testing my scripts in Unity first... \$\endgroup\$ – Alex F Jun 7 at 15:00
  • 1
    \$\begingroup\$ Also I recommend caching a reference instead of performing expensive GetComponent calls every time. \$\endgroup\$ – trollingchar Jun 7 at 16:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.