Search code examples
c#unity-game-enginegame-physicsgame-development

OnCollisionEnter for only one object with same script


The problem is that - when two objects with the same scripts collide, I need to destroy them and create a new object. But they collide eachother and instead of one final object,i have 2 of them.

private void OnCollisionEnter2D(Collision2D collision)
{
    var drop = collision.gameObject.GetComponent<DropBase>();
    if (drop != null)
    {
        Destroy(collision.gameObject);
        Instantiate(_pile, transform.position, Quaternion.identity);
        Destroy(gameObject);
    }
}

I was trying give every of object lifetime,and the longer living object have rights to create new one,but i have situation where thay created at same time,and this method doesn't work.


Solution

  • You can deactive the two game objects before destroying them, then you can ignore the collision if one of the game object is inactive.

    private void OnCollisionEnter2D(Collision2D collision)
    {
        var incomingGameObject = collision.gameObject;
        if(!gameObject.activeSelf || !incomingGameObject.activeSelf)
            return;
    
        var drop = incomingGameObject.GetComponent<DropBase>();
        if (drop != null)
        {
            incomingGameObject.SetActive(false);
            Destroy(incomingGameObject);
            Instantiate(_pile, transform.position, Quaternion.identity);
            gameObject.SetActive(false);
            Destroy(gameObject);
        }
    }