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?
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 has:
Child B has:
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.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With