Physics2D.OverlapBox is inconsistent

Im trying to use OverlapBox to detect if the player is colliding with it.

Basically the object is an item that uses a BoxCollider2D, I set the isTrigger to false so it wont fall off the platform when using a RigidBody2D… I set the LayerMask collision to not interact with the Player and Enemy’s layer mask so Im using a OverlapBox or BoxCast instead.

private void DetectCollision()
    {
        Collider2D _contact = Physics2D.OverlapBox(transform.position, collisionSize, 0f, target);

        if (_contact != null && _contact.gameObject.CompareTag("Player"))
        {
            // do something

            gameObject.SetActive(false);
        }
    }

The problem is, this and BoxCast is inconsistent… it would either not work or dont work as soon as it touches the player.

I dunno what the problem is here, I’ve used it before in one game that I made and it works completely fine.

The above call is extremely basic and hasn’t changed in many many years so the likelyhood of there being a bug there is very low indeed.

Without knowing whether there’s a collider there at that transform.position matching whatever “target” is set too and also if it has the correct tag, it’s impossible to provide any more information.

I can only presume you’ve debugged this code before posting here to check what you are hitting or not, what tag it has etc. If you have a single instance where it’s not detecting something you think it should then maybe you can show that here. Alternately if you have a simple reproduction project then maybe you can share it with me and I’d be happy to take a look.

I know it’s easy to blame Unity but it does just sound like an issue with your set-up/configuration.

1 Like

It was indeed my set-up thats causing the problem…I put the Player, Enemy and Items on the same layermask cuz I thought it would be easier to just use one layer mask on object that wont have to touch each other… its probably detecting itself, and sometimes the player.

So I just used the result list and now it works fine… tnx

private void DetectCollision()
    {
        Physics2D.OverlapBox(transform.position, collisionSize, 0f, filter, contacts);

        if (contacts.Contains(targetCollider))
        {
            // do something
            gameObject.SetActive(false);
        }
    }
1 Like

Thanks for detailing what was wrong! :slight_smile:

1 Like