Skip to main content
4 of 4
Grammar
DMGregory
  • 140.8k
  • 23
  • 257
  • 401

How to create a box collider that surrounds an object and its children?

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;
        }
    }

}
OC_RaizW
  • 1.5k
  • 8
  • 27
  • 49