当同一对象的 2 个实例发生碰撞时,如何只销毁 1 个对象?

How do i destroy only 1 object when 2 instances of the same object collide?

抱歉,我在工作,无法访问我的代码,但基本上。如果我将它设置为销毁 "other" 因为在更新结束之前没有任何东西被销毁,两个对象都被标记为销毁。我现在不在乎哪一个幸存下来只是想了解如何做到这一点的想法。将来我可能会创建一个新实例,其中 2 个命中,但随后两者都会触发新实例的创建,并且 2 个新实例会发生碰撞等。

好吧,你可以制作一面旗帜,告诉你你是否被摧毁了。如果是这样,你不能摧毁任何其他人。然后,首先调用的 'collide' 方法将成为幸存者。它会是这样的:

private bool alreadyDead = false;
void OnCollisionEnter(Collision collision) {
    if (!alreadyDead) {
        MyScript script = collision.gameobject.GetComponent<MyScript>();
        if (script != null) {
             script.alreadyDead = true;
             collision.gameobject.Destroy();
        }
    }
}

您需要设置某种标志以进行检查。您可以在脚本上设置一个布尔值,或者甚至可以切换您想要销毁的游戏对象的活动状态,然后不让禁用的游戏对象通过其 collision/destroying 方法。

void OnCollisionEnter (Collision collision) {
    // Only proceed if this gameObject is active
    if (gameObject.activeSelf) {
        // Disable the other gameObject we've collided with, then flag to destroy it
        collision.gameObject.SetActive(false);
        Destroy(collision.gameObject);
    }
}

我也遇到了同样的问题。经过相当多的挖掘,我想出了这个解决方案:

我有两个蛋在一个 int 网格上产卵,如果它们在产卵时重叠,具有更高实例 ID 的那个将被摧毁。

private void OnTriggerEnter2D(Collider2D other)
{  

    if (other.CompareTag(Tags.Egg))
    { 
        if (this.GetInstanceID() > other.GetInstanceID())
        {
            Destroy(gameObject);
        }
        else
        {
            Destroy(other.gameObject);
        }
    }
}

另一种方法是检查 class Egg 中 Start() 的重叠。 但是我写的代码好像不行。

private void Start()
{
    _rigidbody = GetComponent<Rigidbody2D>();
   
    Collider[] hitColliders = Physics.OverlapBox(gameObject.transform.position, transform.localScale / 2, Quaternion.identity, default);

    //Check when there is an existing collider at the spot coming into contact with the new spawn egg
    if ( hitColliders.Length != 0)
    {
        Destroy(gameObject);
    }

}

第二种方法失败了,由于某种原因,它一直在摧毁所有的刷怪蛋。