I have a bunch of game objects parented to an Empty:
EmptyObject
+- GameObject
+- GameObject
+- ...
+- GameObject
Now I'd like to add a Box Collider to the parent EmptyObject and have it resized to fit all containing GameObjects.
When applying a Collider to a >>>single<<< GameObject, it is being automatically resized to fit. And rightclicking on the collider in the editor and selecting "Reset" also auto-resizes the collider to fit. Is there a way to get this funtionality when dealing with a group of objects?
The following implementation seems to do the trick for me. Simply create a folder in your game project called “Editor” and create a C# script called “ColliderToFit.cs” and paste the following source.
Note: This currently only works for BoxColliders, but it isn’t hard to add support for SphereColliders if necessary
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.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).renderer;
if (childRenderer != null) {
if (hasBounds) {
bounds.Encapsulate(childRenderer.bounds);
}
else {
bounds = childRenderer.bounds;
hasBounds = true;
}
}
}
BoxCollider collider = (BoxCollider)rootGameObject.collider;
collider.center = bounds.center - rootGameObject.transform.position;
collider.size = bounds.size;
}
}
}
This is so awesome, thanks! Really good for my 2d platform game - I just attach this modified version of your script below to a parent empty object, then add child sprite tiles as much as I want and the parent Collider perfectly fits the group of tiles. Cool!
[RequireComponent(typeof(BoxCollider))]
public class BoxColliderToChildrenSize : MonoBehaviour
{
[ContextMenu(“Fit BoxCollider to children”)]
void FitBoxColliderToChildren()
{
var bounds = new Bounds(Vector3.zero, Vector3.zero);
/**
Resizes the collider of gameObject to fit all meshes attached to it. Only works for Box/Shpere collider
*/
public static void ResizeColliderToFitMesh(GameObject sourceObject)
{
Collider collider = sourceObject.GetComponent<Collider>();
Bounds objectBounds = GetMeshBounds(sourceObject);
if (collider.GetType() == typeof(SphereCollider))
{
var sphereCollider = (SphereCollider)collider;
sphereCollider.center = objectBounds.center - sourceObject.transform.position;
sphereCollider.radius = objectBounds.extents.x;
}
else if (collider.GetType() == typeof(BoxCollider))
{
var boxCollider = (BoxCollider)collider;
boxCollider.center = objectBounds.center - sourceObject.transform.position;
boxCollider.size = objectBounds.size;
}
}