I have a car that needs a box collider.
If the car were 1 single mesh, I would only need to call:
boxCol = gameObject.AddComponent<BoxCollider>();
and it would create a BoxCollider
that perfectly fits my car, based on my car's mesh.
Now I have a car which consists of many different parts in the transformation hierarchy. (For example: the body of the car is the parent of the 4 doors. Every door is a separate game object, and has a doorknob child, etc.)
Now I need a script that changes the BoxCollider
so that its box surrounds the whole car, including all of these parts.
I found this pose on Unity Answers, but it just doesn't get me the right collider.
Here is the code I'm using:
using UnityEngine;
using UnityEditor;
using System.Collections;
public class ColliderToFit : MonoBehaviour
{
[MenuItem("My Tools/Collider/Fit to Children")]
static void FitToChildren()
{
foreach (GameObject rootGameObject in Selection.gameObjects)
{
if (!(rootGameObject.GetComponent<Collider>() is BoxCollider))
continue;
bool hasBounds = false;
Bounds bounds = new Bounds(Vector3.zero, Vector3.zero);
for (int i = 0; i < rootGameObject.transform.childCount; ++i)
{
Renderer childRenderer = rootGameObject.transform.GetChild(i).GetComponent<Renderer>();
if (childRenderer != null)
{
if (hasBounds)
{
bounds.Encapsulate(childRenderer.bounds);
}
else
{
bounds = childRenderer.bounds;
hasBounds = true;
}
}
}
BoxCollider collider = (BoxCollider)rootGameObject.GetComponent<Collider>();
collider.center = bounds.center - rootGameObject.transform.position;
collider.size = bounds.size;
}
}
}