Search code examples
c#unity-game-enginecollision-detection

Unity - OnTriggerStay2D() for 2 colliders simultaneously


I'm using an OnTriggerStay2D() function that does something while an object in inside the collider (doesn't matter what). However, sometimes I have another, so a total of 2 colliders that may stay inside that collider. The two colliders are not on the same Game Object. I'm trying like this:

void OnTriggerStay2D(Collider2D other)
{
    if (other.gameObject.CompareTag("Obj1"))
    {
        //do something
    } 
    if (other.gameObject.CompareTag("Obj2"))
    {
        //do something else
    }
}

but do something else just never happens when Obj1 is already inside. How to make a collider sense two colliders at once for OnTriggerStay2D()?

EDIT TO CLARIFY:

The OnTriggerStay2D() still gets called. The issue is that the code never gets to the if statement where I have to do something else comment.


Solution

  • When the OnTriggerStay2D function is called, it does not report multiple GameObjects that is touching. It returns one trigger/Collider2D information only. After the next physics frame or so, it will be called again. This time it will return the other trigger/Collider2D information that is touching the-same GameObject.

    In your case, after Obj1 is returned, OnTriggerStay2D will be called in the next physics frame or so with Obj2 returned.