2 OnTriggerEnter2D collision functions are reacting when I only call one

Hi all, I am making a 2D multiplayer attack game and I have 2 mirror scripts with on trigger enter. So when one of them attacks, and the other gets hit, it should destroy the one that gets hit, but it destroys both of the players. Here are the 2 mirror script’s OnTriggerEnter2D functions:

private void OnTriggerEnter2D(Collider2D other)
{
    if (other.gameObject.tag == "player2")
    {
        Destroy(GameObject.Find("Player2")); 

        Debug.Log("Player 2 died");
    }
}

and:

private void OnTriggerEnter2D(Collider2D other)
{
    if (other.gameObject.tag == "player1")
    {
        Destroy(GameObject.Find("Player1"));

        Debug.Log("Player 1 died");
    }
}

Thanks, Larry

Instead of Destroy(GameObject.Find…) use Destroy(gameObject).

Unity and c# is very case sensitive, it seems that you’re using “player1” AND “Player1” maybe thats your issue- and like madsks13 said, if you just want it to destroy itself “gameObject” refers to its own gameobject while GameObject refers to an object specifically - Again case sensitive.

Also find is a very expensive method, but obviously works pretty well. And if like the code says you’re just refering to a tag, then never mind all that.

Hi all, I don’t think that madks13 and fr0stp1k3’s answers are correct because even if I try a different method and simply do this…

private void OnTriggerEnter2D(Collider2D other)
{
    if (other.gameObject.tag == "player2")
    {
        Debug.Log("player 2 died");
    }
}

and this:

private void OnTriggerEnter2D(Collider2D other)
{
    if (other.gameObject.tag == "player1")
    {
        Debug.Log("player 1 died");
    }
}

it still doesn’t work :frowning:
@madks13 @fr0stsp1k3
thanks, larry