@@ -14,33 +14,40 @@ static void FixSize(MenuCommand command)
14
14
{
15
15
BoxCollider col = ( BoxCollider ) command . context ;
16
16
17
- // record undo
17
+ // Record undo for undo functionality
18
18
Undo . RecordObject ( col . transform , "Fit Box Collider To Children" ) ;
19
19
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 ) ;
22
22
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 ;
26
26
}
27
27
28
- public static Bounds GetRecursiveMeshBounds ( GameObject go )
28
+ public static Bounds GetLocalBounds ( Transform parent )
29
29
{
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 ++ )
41
40
{
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 ) ) ;
43
48
}
49
+
50
+ return bounds ;
44
51
}
45
52
}
46
53
}
0 commit comments