@@ -14,33 +14,40 @@ static void FixSize(MenuCommand command)
1414 {
1515 BoxCollider col = ( BoxCollider ) command . context ;
1616
17- // record undo
17+ // Record undo for undo functionality
1818 Undo . RecordObject ( col . transform , "Fit Box Collider To Children" ) ;
1919
20- // get child mesh bounds
21- var b = GetRecursiveMeshBounds ( col . gameObject ) ;
20+ // Get transformed bounds relative to the collider object
21+ Bounds localBounds = GetLocalBounds ( col . transform ) ;
2222
23- // set collider local center and size
24- col . center = col . transform . root . InverseTransformVector ( b . center ) - col . transform . position ;
25- col . size = b . size ;
23+ // Set collider local center and size
24+ col . center = localBounds . center ;
25+ col . size = localBounds . size ;
2626 }
2727
28- public static Bounds GetRecursiveMeshBounds ( GameObject go )
28+ public static Bounds GetLocalBounds ( Transform parent )
2929 {
30- var r = go . GetComponentsInChildren < Renderer > ( ) ;
31- if ( r . Length > 0 )
32- {
33- var b = r [ 0 ] . bounds ;
34- for ( int i = 1 ; i < r . Length ; i ++ )
35- {
36- b . Encapsulate ( r [ i ] . bounds ) ;
37- }
38- return b ;
39- }
40- else // TODO no renderers
30+ var renderers = parent . GetComponentsInChildren < Renderer > ( ) ;
31+ if ( renderers . Length == 0 )
32+ return new Bounds ( Vector3 . zero , Vector3 . zero ) ; // No renderers
33+
34+ // Initialize bounds in local space
35+ Bounds bounds = new Bounds ( parent . InverseTransformPoint ( renderers [ 0 ] . bounds . center ) ,
36+ parent . InverseTransformVector ( renderers [ 0 ] . bounds . size ) ) ;
37+
38+ // Encapsulate all child renderers
39+ for ( int i = 1 ; i < renderers . Length ; i ++ )
4140 {
42- return new Bounds ( Vector3 . one , Vector3 . one ) ;
41+ var worldBounds = renderers [ i ] . bounds ;
42+
43+ // Convert world bounds to local space
44+ Vector3 localCenter = parent . InverseTransformPoint ( worldBounds . center ) ;
45+ Vector3 localSize = parent . InverseTransformVector ( worldBounds . size ) ;
46+
47+ bounds . Encapsulate ( new Bounds ( localCenter , localSize ) ) ;
4348 }
49+
50+ return bounds ;
4451 }
4552 }
4653}
0 commit comments