Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unity - How to detect collision on a child object from the parent GameObject?

I am making a 2D Game with Unity 5 and I have a problem with child GameObject collider. I want to detect a collision between a Child GameObject with another object, doing this from the parent script and using tags.

Follow my parent script below:

 void OnCollisionEnter2D(Collision2D hit) {

    if(hit.transform.tag == "Enemy"){

        this.playerRigidbody.AddForce(new Vector2(0, this.forceJump));

    }

 }

The "Enemy" tag is another object that is colliding with the collider of my player child. I want to detect the collision between the child object and that another object, I searched in many similar forums about Unity but I couldn't solve my problem. Someone can help me with this problem?

like image 679
Yuri Pires Avatar asked Jan 29 '17 22:01

Yuri Pires


1 Answers

When a collision occurs, Unity will search up the hierarchy for the nearest Rigidbody and run any scripts on that same GameObject.

So, the simple approach is to make sure the rigidbody is on the parent object with the script. Here's an example hierarchy:

  • Parent
    • Child A
      • Child B

Parent has:

  • A Rigidbody 2D
  • The script

Child B has:

  • A Box Collider 2D

When the box collider collides with something, the event will bubble up straight through Child A and be received by the Rigidbody on the parent, which will then cause the script to run.

If you can't put the rigidbody on the parent..

Unity won't bubble the event up the hierarchy any further than that for performance reasons. So, your other options are..

  • Add a script to the child which catches the collision and deals with it there. If you need to, you could forward the event to the parent script like so:

    void OnCollisionEnter2D(Collision2D hit) {
    
        // Forward to the parent (or just deal with it here).
        // Let's say it has a script called "PlayerCollisionHelper" on it:
        PlayerCollisionHelper parentScript = transform.parent.GetComponent<PlayerCollisionHelper>();
    
        // Let it know a collision happened:
        parentScript.CollisionFromChild(hit);
    
    }
    
    • Or a script on the "another" object in order to catch that collision event from its point of view instead.
like image 183
Luke Briggs Avatar answered Oct 03 '22 06:10

Luke Briggs