I have a Car, who needs a Box Collider. If the car would be 1 single mesh, i would only need to call:
boxCol = gameObject.AddComponent<BoxCollider>();
and it would create a boxCollider, which fits perfectly my car, based on my car's mesh.
Now I have a car which exists of many different parts in the hierarchy. (for example: Body of the car is the parent of the 4 doors. Every door is 1 seperate gameobject, and has a doorknob child etc. )
now i need a script which changes the boxCollider so, that it has the box surrounding the whole car.
i found: http://answers.unity3d.com/questions/22019/auto-sizing-primitive-collider-based-on-child-mesh.html
but it just doesnt get me the right collider.
Edit: I just tried again - and the Boxcollider stays the same.
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;
}
}
}