简体   繁体   English

连接到刚体时获取统一对撞机的游戏对象

[英]Get gameobject of unity collider when it is attached to a rigidbody

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. 我在每个子对象上都有一个OnCollisionEnter2D(Collision2D coll)(其中有碰撞器),但是当它们使用coll.gameObject与另一个组碰撞时,返回的游戏对象始终是父对象,而不是单个子对象。

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. 注意2:我也看到了使用触发器的选项,但是我更喜欢碰撞,因为它也可以处理物理问题。

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. 显然,我可以在碰撞中使用第一个碎片,因为它是OnCollisionEnter2D所在的类,但是我无法找到一种方法来使第二个碎片碰撞。

You're trying to get the gameObject property of the Collision2D object when you really want the gameObject properties of the Collider2D itself. 你试图让gameObject的财产Collision2D对象时,你真正想要的gameObject的属性Collider2D本身。 Collision2D has the collider and otherCollider properties that you can use: Collision2D具有可使用的colliderotherCollider属性:

private void OnCollisionEnter2D(Collision2D coll)
{
    Debug.Log(coll.collider.gameObject.name);
    Debug.Log(coll.otherCollider.gameObject.name);
    ...   
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM