Unity Physics.OverlapBox just doesn't work
Asked Answered
M

2

0

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?

Midi answered 1/6, 2017 at 15:56 Comment(0)
A
1

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

Attrahent answered 1/6, 2017 at 16:7 Comment(0)
C
2

I had this same issue. I was using TransformVector to calculate the size of my box:

Vector3 size = itemTransform.TransformVector(itemCollider.size / 2);
Collider[] results = Physics.OverlapBox(itemTransform.position, size);

The results weren't consistent. I realised that TransformVector was returning negative values for the size so I simply had to Mathf.Abs the Vector:

Vector3 size = itemTransform.TransformVector(itemCollider.size / 2);
size.x = Mathf.Abs(size.x);
size.y = Mathf.Abs(size.y);
size.z = Mathf.Abs(size.z);
Collider[] results = Physics.OverlapBox(itemTransform.position, size);
Cindycine answered 1/9, 2017 at 7:26 Comment(0)
A
1

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

Attrahent answered 1/6, 2017 at 16:7 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.