Dynamically loaded FBX - BoxCollider sizing isn't working

Here’s my code to generate a boxCollider on a component after importing the FBX file. Some objects are scaled and rotated in the FBX so that might be one of the issues. But the size and center are never correct. I’ve tried a few ways of converting to world sizing but nothing works.

                MeshRenderer meshRenderer = child.GetComponent<MeshRenderer>();

                if (meshRenderer != null)
                {

                    BoxCollider boxCollider = child.gameObject.AddComponent<BoxCollider>();
                    Bounds bounds = meshRenderer.bounds;
                    Vector3 localSize = bounds.size;
                    boxCollider.size = localSize;
                    boxCollider.center = bounds.center;

                }

The boxCollider.center is the local offset of the center relative to the objects local space, not the world space position of the center. If the object is scaled you run into more issues as even the size would not fit either. The bounds of the renderer are always worldspace bounds. What you should read is the meshes bounds instead. The renderers bounds is always world space aligned and would enclose the mesh.bounds which is defined in local space. So try meshRenderer.sharedMesh.bounds instead.

meshRenderer doesn’t have sharedMesh inside of it. Am I missing something?

Yes, my bad. The normal MeshRenderer doesn’t directly reference the mesh. The sharedMesh is on the MeshFilter component. The SkinnedMeshRenderer does have a direct reference to the mesh.

My man! That worked perfectly. Thank you!