Physics.OverlapBoxNonAlloc is not working as expected, it does not correctly detect objects

Hi everyone, I am making a tool for Unity to scatter some prefabs.

In order to check if a prefab will overlap with another, I am doing the following thing.

Take the BoxCollider (set as trigger) size and center of the prefab and check if at the wished location another objects is present.

To do so, I am using the Physics.OverlapBoxNonAlloc, here is the code:

public class Scatter : MonoBehaviour {

        [SerializeField] GameObject prefab;
        [SerializeField] LayerMask layerMask;
        [SerializeField] Grid grid;

        BoxCollider boxCollider;

        [ContextMenu("Scatter Prefabs")]
        public void ScatterPrefab()
        {
            ResetScatter();

            boxCollider = prefab.GetComponent<BoxCollider>();
            Vector2 space = new Vector2(grid.size.x / (grid.num.x - 1), grid.size.y / (grid.num.y - 1));

            GameObject go;
            float posY, posX;
            int count = 0;
            Collider[] bufferColliders = new Collider[2];
            for (int y = 0; y < grid.num.y; y++)
            {
                posY = y * space.y - grid.size.y / 2;
                for (int x = 0; x < grid.num.x; x++)
                {
                    posX = x * space.x - grid.size.x / 2;

                    Vector3 pos = new Vector3(posX, 0, posY);

                    int num = Physics.OverlapBoxNonAlloc(pos + boxCollider.center, boxCollider.size / 2, bufferColliders, Quaternion.identity, layerMask);

                    GameObject cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
                    cube.transform.SetParent(transform);
                    cube.name = "CheckBox " + count;
                    cube.transform.localPosition = pos + boxCollider.center;
                    cube.transform.localScale = boxCollider.size;
                    DestroyImmediate(cube.GetComponent<BoxCollider>());

                    Debug.DrawRay(cube.transform.position, Vector3.up * 0.2f, Color.red, 10);

                    foreach (var col in bufferColliders)
                    {
                        Debug.Log(cube.name + " collides with: " + col);
                    }

                    if (num == 0)
                    {
                        go = PrefabUtility.InstantiatePrefab(prefab) as GameObject;
                        go.name += " " + count;
                        go.transform.SetParent(transform);
                        go.transform.localPosition = pos;

                        DestroyImmediate(cube);
                    }

                    count++;
                }
            }
        }

        void OnDrawGizmosSelected()
        {
            Gizmos.color = Color.red;
            Gizmos.DrawWireCube(transform.position, grid.size3);
        }

        [ContextMenu("Reset Scatter")]
        public void ResetScatter()
        {
            for (int i = transform.childCount - 1; i >= 0; i--)
                DestroyImmediate(transform.GetChild(i).gameObject);
        }

        [System.Serializable]
        class Grid {

            public Vector2 size = Vector2.one;
            public Vector2Int num = Vector2Int.one;

            #region Getter & Setter

            public Vector3 size3 => new Vector3(size.x, 0, size.y);

            #endregion
        }
    }

Where a checking is done, I have instanciate a cube to see if it is the right box checking but here is the result:

The prefab is correcly instanciate, but the following are completly wrong, no prefab has been instantiate since the OverlapBox says that it collides with the first one whereas there are not event touching it.

As tou can see with the above picture, with a larger scale, it is a real mess, many prefabs are overlapping with others.

Wow, that is a lot of code… here was my deconfliction approach:

And here it is in 2D:

Simple, simple, simple, one check, succeed or fail.

If you want to debug the above, start with why the red box doesn’t match the green collider and go from there.

Time to start debugging! Here is how you can begin your exciting new debugging adventures:

You must find a way to get the information you need in order to reason about what the problem is.

Once you understand what the problem is, you may begin to reason about a solution to the problem.

What is often happening in these cases is one of the following:

  • the code you think is executing is not actually executing at all
  • the code is executing far EARLIER or LATER than you think
  • the code is executing far LESS OFTEN than you think
  • the code is executing far MORE OFTEN than you think
  • the code is executing on another GameObject than you think it is
  • you’re getting an error or warning and you haven’t noticed it in the console window

To help gain more insight into your problem, I recommend liberally sprinkling Debug.Log() statements through your code to display information in realtime.

Doing this should help you answer these types of questions:

  • is this code even running? which parts are running? how often does it run? what order does it run in?
  • what are the names of the GameObjects or Components involved?
  • what are the values of the variables involved? Are they initialized? Are the values reasonable?
  • are you meeting ALL the requirements to receive callbacks such as triggers / colliders (review the documentation)

Knowing this information will help you reason about the behavior you are seeing.

You can also supply a second argument to Debug.Log() and when you click the message, it will highlight the object in scene, such as Debug.Log("Problem!",this);

If your problem would benefit from in-scene or in-game visualization, Debug.DrawRay() or Debug.DrawLine() can help you visualize things like rays (used in raycasting) or distances.

You can also call Debug.Break() to pause the Editor when certain interesting pieces of code run, and then study the scene manually, looking for all the parts, where they are, what scripts are on them, etc.

You can also call GameObject.CreatePrimitive() to emplace debug-marker-ish objects in the scene at runtime.

You could also just display various important quantities in UI Text elements to watch them change as you play the game.

Visit Google for how to see console output from builds. If you are running a mobile device you can also view the console output. Google for how on your particular mobile target, such as this answer for iOS: How To - Capturing Device Logs on iOS or this answer for Android: How To - Capturing Device Logs on Android

If you are working in VR, it might be useful to make your on onscreen log output, or integrate one from the asset store, so you can see what is happening as you operate your software.

Another useful approach is to temporarily strip out everything besides what is necessary to prove your issue. This can simplify and isolate compounding effects of other items in your scene or prefab.

If your problem is with OnCollision-type functions, print the name of what is passed in!

Here’s an example of putting in a laser-focused Debug.Log() and how that can save you a TON of time wallowing around speculating what might be going wrong:

“When in doubt, print it out!™” - Kurt Dekker (and many others)

Note: the print() function is an alias for Debug.Log() provided by the MonoBehaviour class.

Change line 30 to:

int num = Physics.OverlapBoxNonAlloc(pos, prefab.transform.localScale/2, bufferColliders, Quaternion.identity, layerMask);
1 Like

The problem is, my object has a scale of 1 but its size is 0.2 meters so if I check for a cubic meter whereas my object is only 0.2^3 m3, it going to be too much

I finally find the problem, it does not come from the code but how unity manage colliders and transform. I don’t fully understand how it works but the best thing to do is to use Physics.SyncTransforms which make unity resync every transform of game objects.

I have found this thread which mentioned this.