OnTriggerEnter2D/Exit2D is inconsistent when Object overlaps several colliders

I have a large collider that can overlap several other GameObjects with colliders at once. This means that sometimes OnTriggerExit2D is called even if I’m still colliding with another GameObject. I’ve tried using OnTriggerStay2D instead of Enter, and while that is better, it still gets 1 frame of OnTriggerExit being called every time I exit a GameObjects collider.

How can I make sure that while my Object is colliding with something, it will stay in that state, and not change state until it is completely collision free. i.e Using the code below, how can “isColliding” stay true until no GameObjects are overlapping the collider?

private void OnTriggerStay2D(Collider2D collision) //or OnTriggerEnter2D
    {
        isColliding = true;
    }

    private void OnTriggerExit2D(Collider2D collision)
    {
        isColliding = false;
    }

Edit: If using a Raycast you can just do “if(collider == null)”, is there something similar I could use here?

I’m curious, when you say you get an exit but you’re still inside, is that because something really did exit but you still have more but you’re only “counting” with a bool?

Your exactly right, I realized this and changed my code to:

private bool CanPlace()
    {
        if(colliders.Count > 0)
        {
            TurnRed();
            return false;
        }
        TurnGreen();
        return true;
    }

    private void OnTriggerEnter2D(Collider2D collision)
    {
        colliders.Add(collision);
    }

    private void OnTriggerExit2D(Collider2D collision)
    {
        colliders.Remove(collision);
    }

I’ll leave this here in case anyone runs into a similar issue since I couldnt find anything really explaining this.

Cool, you took the answer I was aiming at, if that had been the case :slight_smile:

Note, maybe not super important, but if you do not care about the collider (individually), an int would probably work all the same…

Glad it’s working for ya, regardless :wink:

1 Like