-
Notifications
You must be signed in to change notification settings - Fork 0
/
DynamicColliderSize.cs
50 lines (43 loc) · 1.38 KB
/
DynamicColliderSize.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
using UnityEngine;
// Dynamically set the size of the attached collider to cover all the children objects.
[RequireComponent(typeof(BoxCollider))]
public class DynamicColliderSize : MonoBehaviour
{
[SerializeField] Transform boardVisual;
void OnEnable()
{
ApplySize();
}
void ApplySize()
{
var boxCol = gameObject.GetComponent<BoxCollider>();
if (boxCol == null)
{
boxCol = gameObject.AddComponent<BoxCollider>();
}
Bounds bounds = new Bounds(Vector3.zero, Vector3.zero);
bool boundsInitialized = false;
var allDescendants = boardVisual.GetComponentsInChildren<Transform>();
foreach (Transform desc in allDescendants)
{
Renderer childRenderer = desc.GetComponent<Renderer>();
if (childRenderer != null && childRenderer.enabled)
{
if (!boundsInitialized)
{
bounds = new Bounds(childRenderer.bounds.center, childRenderer.bounds.size);
boundsInitialized = true;
}
else
{
bounds.Encapsulate(childRenderer.bounds);
}
}
}
if (boundsInitialized)
{
boxCol.center = bounds.center - transform.position;
boxCol.size = bounds.size;
}
}
}