I had the same issue, hopefully, this will help somebody some daysomeday.
//first get all possible mesh renderers
First, get all possible mesh renderers:
var renderers = gameObject.GetComponentsInParent<Renderer>().ToList();
renderers.AddRange(gameObject.GetComponentsInChildren<Renderer>());
// set the center of initial bounds to the position of the parent object and size to zero, and then encapsulate every mesh
Set the center of initial bounds to the position of the parent object and size to zero, and then encapsulate every mesh:
var bounds = new Bounds(transform.position, Vector3.zero);
foreach (var r in renderers)
{
bounds.Encapsulate(r.bounds);
}
//add the collider to the parent object and set the size and center for the collider, keep in mind the assumption here is that the position of object is 0
Add the collider to the parent object and set the size and center for the collider, keep in mind the assumption here is that the position of the object is 0:
var spaceCollider = gameObject.AddComponent<BoxCollider>();
var c = spaceCollider.center;
spaceCollider.center = new Vector3(c.x, c.y + bounds.size.y / 2, c.z);
spaceCollider.size = bounds.size;
spaceCollider.isTrigger = true;