I have a game object that has a rigidbody and then a group of sub game objects with sprites and colliders where each collider is attached to the parent's rigidbody. This works well for the physics and collisions as the entire group of objects will bounce and collide off of the scenery. However, when two groups collide I want their to be damage on one of the individual sub game objects. I have a OnCollisionEnter2D(Collision2D coll) on each of the sub objects(Which have the collider on them) however, when they collide with another group using coll.gameObject the returned game object is always the parent and not the individual sub object.
Long Story Short: Is there any way to get the game object of a collider when it is attached to another game object with a rigid body?
Note: I have seen some solutions that use a ray cast to find the object but it seems like a lot of unnecessary work.
Note 2: I have also seen options that use trigger but i prefer the collision as it handles physics as well.
private void OnCollisionEnter2D(Collision2D coll)
{
Debug.Log(coll.gameObject.name); // Showing the parent
ShipPiece sp = coll.gameObject.GetComponent<Piece>(); // Looking for the individual piece
if (sp != null)
{
// Apply the damage to the other piece based off the weight of this piece
coll.gameObject.SendMessage("ApplyDamage", weight*10);
}
}
Obviously I can can the first Piece in the collision as it is the class where OnCollisionEnter2D exists, but I cannot figure out a way to get the second Piece which its colliding into.
You're trying to get the gameObject
property of the Collision2D
object when you really want the gameObject
properties of the Collider2D
itself. Collision2D
has the collider
and otherCollider
properties that you can use:
private void OnCollisionEnter2D(Collision2D coll)
{
Debug.Log(coll.collider.gameObject.name);
Debug.Log(coll.otherCollider.gameObject.name);
...
}
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