Search code examples
c#unity-game-enginecollision-detectiongame-enginegame-physics

Multiple triggers in Unity


Reference image

I have a certain object in my game and I'm trying to see whether the object triggers multiple triggers. I tried with the code bellow but for some reason it doesn't work.

void OnTriggerEnter2D(Collider2D col)
{
    if (col.tag == "speed")
    {
        //do something
    }
    else if (col.tag == "speed" && col.tag == "point")
    {
        //do something
    }
}

How can I recognize if the object only hit "Col1" or "Col1" and "Col2"


Solution

  • OnTriggerEnter is only called when your object is colliding with one specific trigger. Thus, the tag of the collider (col) can't be speed and point at the same time.

    You have to track if the object is colliding with your triggers using a boolean variable for example :

    private bool collidingWithSpeed;
    private bool collidingWithPoint;
    
    void OnTriggerEnter2D(Collider2D col)
    {
        if (col.CompareTag("speed"))
        {
            collidingWithSpeed = true ;
            //do something
        }
        else if (col.CompareTag("point"))
        {
            collidingWithPoint = true ;
            //do something
        }
    
        if( collidingWithSpeed && collidingWithPoint )
        {
             // Do something when your object collided with both triggers
        }
    }
    // Don't forget to set the variables to false when your object exits the triggers!
    void OnTriggerExit2D(Collider2D col)
    {
        if (col.CompareTag("speed"))
        {
            collidingWithSpeed = false;
        }
        else if (col.CompareTag("point"))
        {
            collidingWithPoint = false;
        }
    }