Create a box collider and auto set the dimensions on runtime

Hi, I generate my entire level on runtime and I need to create a box collider as a trigger around each level.

My hierarchy is created at runtime and looks like this

Level1
--Room1
----Tile1
----Tile2
----Tile3
--Room2
----Tile1
----Tile2
----Tile3

Each room is created from a bunch of prefab tiles, so I need the box collider to detect the size of the gameobject “Room1” and create a collider the entire size of that.

I can add the box collider to the room and set it as a trigger, but I don’t know how to create one that is the entire size of the room itself.

I was thinking that it would be best to add these last in the level build process. For example, when the level is complete, run a function to add all “rooms” to an array and then go through the array one by one adding the collider.

Any help with how to autosize the collider would be appreciated.

BoxCollider should be automatically scale when it is attached

BoxCollider boxCollider = gameObject.AddComponent<BoxCollider>();

If you want to manually scale the boxcollider you can use the following

MeshRenderer renderer=gameObject.getcomponent<MeshRenderer>();
boxCollider.center = renderer.bounds.center;
boxCollider.size = renderer.bounds.size;