-
Notifications
You must be signed in to change notification settings - Fork 5
/
PopFitCollider.cs
61 lines (49 loc) · 1.68 KB
/
PopFitCollider.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
#if UNITY_EDITOR
using UnityEditor;
#endif
public class PopFitCollider : MonoBehaviour {
#if UNITY_EDITOR
[MenuItem("NewChromantics/Collider/Fit collider to Children")]
static void FitColliderToChildren() {
foreach (GameObject rootGameObject in Selection.gameObjects) {
if (!(rootGameObject.GetComponent<Collider>() ))
continue;
Renderer[] ChildRenderers = rootGameObject.GetComponentsInChildren<Renderer>();
Renderer[] ThisRenderers = rootGameObject.GetComponents<Renderer>();
var Renderers = new Renderer[ChildRenderers.Length + ThisRenderers.Length];
ChildRenderers.CopyTo(Renderers, 0);
ThisRenderers.CopyTo(Renderers, Renderers.Length);
bool hasBounds = false;
Bounds bounds = new Bounds(Vector3.zero, Vector3.zero);
foreach( Renderer r in Renderers )
{
if (hasBounds) {
bounds.Encapsulate(r.bounds);
}
else {
bounds = r.bounds;
hasBounds = true;
}
}
// set all collider components
if ( rootGameObject.GetComponent<Collider>() is BoxCollider )
{
BoxCollider collider = (BoxCollider)rootGameObject.GetComponent<Collider>();
collider.center = bounds.center - rootGameObject.transform.position;
collider.size = bounds.size;
}
if ( rootGameObject.GetComponent<Collider>() is CapsuleCollider )
{
CapsuleCollider collider = (CapsuleCollider)rootGameObject.GetComponent<CapsuleCollider>();
collider.center = bounds.center - rootGameObject.transform.position;
Debug.Log(bounds);
collider.height = (bounds.max.y - bounds.min.y) * 1.0f;
collider.radius = (bounds.max.x - bounds.min.x) * 0.5f;
}
}
}
#endif
}