Problem with box collider generated via script

Hello to all!

I have the following issue: I’m trying to add a boxCollider component to a set of quads that I’m generating via script (the box collider is also generated via script). I’m using the following code to generate the collider:

BoxCollider col = gameObject.AddComponent ();
col.center = Vector3.zero;
col.size = new Vector3(this.size, this.size);

Where size is the side length of the object I’m generating (VoxelMap is a gameObject that contains 4 grids, each made with quads). This chunk of code is being called from the awake method, right after generating and positioning the grid children (they are positioned so that VoxelMap gameObject’s position is at the center of all 4 grids).

The issue is that the collider always generates with a small offset in box the x and y axis. And this seems to be because the 4 grid children that compose the VoxelMap gameObject move slightly when the collider is created. Here are some pictures describing the situation:


This is the map of grids being generated with the collider (it has 4 grids, and its center should be in the exact middle of the grids). The collider is centered allright, and the gameObject’s position is at origin. But the 4 grid children are not positioned around the origin.

Now, If I eliminate the component while in runtime:


The 4 grids now are positioned so that the VoxelMap is exactly in the middle. This is also the case If I comment the script code of creating the boxCollider component (never generating the collider in the first place).

So, what could it be that I’m missing? Because I know it must be some dumb detail (I’m still a bit noobish when it comes to unity, and I promise that I searched all over google before making this thread).

Thanks in advance!!

Why not instantiate prefabs of cubes with Colliders?
I think that would be a lot better for the performance too.

TBH, I’m following a tutorial in which they use this method. I do not know if later I’ll change it to use prefabs with their own colliders, but I still want to know why creating the collider seems to mess with the position of the gameObject’s children.

I seem to have found the issue. I was defining the center of the object wrong. The center and pivot were not aligned, and the collider was being defined taking the pivot position, not the center one.