Detecting certain colliders on my game object with OnTriggerEnter2D

Viewed 94

So, I have an enemy game object with 2 triggers attached to it. What I want to achieve is that the enemy will do a separate attack depending on which trigger the player has collided with. So there is a left trigger and a right trigger and these triggers have been saved into a public array on the enemy game object. Here is the code that I thought would achieve the goal however, the if else statement always returns false when it should be returning true.

private void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.gameObject.tag == "ThePlayer")
        {
            if (collision == DamageTriggers[0])
            {
                LeftClawAttack();
            }
            else if (collision == DamageTriggers[1])
            {
                RightClawAttack();
            }
            else
            {
                Debug.Log("False");
            }
        }
    }

If anyone can show me what I am doing wrong here and help me to find a solution to this problem it will be greatly appreciated.

1 Answers

Thanks to Jadon Wolfgang I have been able to figure out why my code wasn't working. So the problem was that I was comparing Box Colliders and not collisions, so to fix this problem I found that you can use a function called IsTouching()

    private void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.gameObject.tag == "ThePlayer")
        {
            if (DamageTriggers[0].IsTouching(collision))
            {
                LeftClawAttack();
            }
            else if (DamageTriggers[1].IsTouching(collision))
            {
                RightClawAttack();
            }
            else
            {
                Debug.Log("False");
            }
        }
    }

Here is the new code if anyone else was having a similar problem.

Related