File tree Expand file tree Collapse file tree 1 file changed +45
-0
lines changed
Expand file tree Collapse file tree 1 file changed +45
-0
lines changed Original file line number Diff line number Diff line change 1+ // Adjust Box Collider to fit child meshes inside
2+ // usage: You have empty parent transform, with child meshes inside, add box collider to parent then use this
3+
4+ using UnityEngine ;
5+ using UnityEditor ;
6+
7+ namespace UnityLibrary
8+ {
9+ public class BoxColliderFitChildren : MonoBehaviour
10+ {
11+ [ MenuItem ( "CONTEXT/BoxCollider/Fit to Children" ) ]
12+ static void FixSize ( MenuCommand command )
13+ {
14+ BoxCollider col = ( BoxCollider ) command . context ;
15+
16+ // record undo
17+ Undo . RecordObject ( col . transform , "Fit Box Collider To Children" ) ;
18+
19+ // get child mesh bounds
20+ var b = GetRecursiveMeshBounds ( col . gameObject ) ;
21+
22+ // set collider local center and size
23+ col . center = col . transform . root . InverseTransformVector ( b . center ) - col . transform . position ;
24+ col . size = b . size ;
25+ }
26+
27+ public static Bounds GetRecursiveMeshBounds ( GameObject go )
28+ {
29+ var r = go . GetComponentsInChildren < Renderer > ( ) ;
30+ if ( r . Length > 0 )
31+ {
32+ var b = r [ 0 ] . bounds ;
33+ for ( int i = 1 ; i < r . Length ; i ++ )
34+ {
35+ b . Encapsulate ( r [ i ] . bounds ) ;
36+ }
37+ return b ;
38+ }
39+ else // TODO no renderers
40+ {
41+ return new Bounds ( Vector3 . one , Vector3 . one ) ;
42+ }
43+ }
44+ }
45+ }
You can’t perform that action at this time.
0 commit comments