Search code examples
c#collision-detectionunity-game-enginegame-physics

Unity Physics.OverlapBox just doesn't work


So there is a problem that whenever I use Physics.OverlapBox to check how many objects in that area exist it always output 0.

Here is my stripped down code:

void Update () {
a();
}

void a()
{
Collider[] c = Physics.OverlapBox(new Vector3(10, 10,10), new Vector3(-10, -10, -10));
Debug.Log(c.Length);
}

My scene setup:

  1. A simple cube placed at position(0,0,0) with scale of (1,1,1)
  2. An empty object where I attach this script

As you can see, my OverlapBox bounds are much bigger than my cube, so it should find my cube, right? Well, no. The output I get from the console is 0.

One more thing: if I set the scale of that cube to something higher than 40 in all axis, the script finally detects my cube and outputs 1.

How do I get this working so the script would find my cube with default scale?


Solution

  • According to the documentation, you are setting the size of the overlapping box to -20, -20, -20, which is not quite logic. It could explain why you have to set the scale of your cube to something bigger than 40, 40, 40.

    Also, Physics-related operations should be processed in the FixedUpdate function instead of the Update one