I'd like to get an object-oriented bounding box (OOBB), rather than an axis oriented bounding box (AABB) for a hierarchy of nodes rather than just a single node. Based on stuff I saw in UnityAnswers and on the forums, I came up with this C# function:
public static Bounds getMeshBounds(GameObject root)
{
//Get all the mesh filters in the tree.
MeshFilter[] filters = root.GetComponentsInChildren<MeshFilter>();
//Construct an empty bounds object w/o an extant.
Bounds bounds = new Bounds(Vector3.zero, Vector3.zero);
bool firstTime = true;
//For each mesh filter...
foreach(MeshFilter mf in filters)
{
//Pull its bounds into the overall bounds. Bounds are given in
//the local space of the mesh, but we want them in world space,
//so, tranform the max and min points by the xform of the object
//containing the mesh.
Vector3 maxWorld = mf.transform.TransformPoint(mf.mesh.bounds.max);
Vector3 minWorld = mf.transform.TransformPoint(mf.mesh.bounds.min);
//If no bounds have been set yet...
if(firstTime)
{
firstTime = false;
//Set the bounding box to encompass the current mesh, bounds,
//but in world coordinates.
bounds = new Bounds((maxWorld + minWorld ) / 2, //center
maxWorld - minWorld ); //extent
}
else //We've started a bounding box. Make sure it ecapsulates
{ //the current mesh extrema.
bounds.Encapsulate(maxWorld);
bounds.Encapsulate(minWorld);
}
}
//Return the bounds just computed.
return bounds;
}
It works when the objects are moved or scaled, but not when they're rotated. When object are rotated, the bounding box not only doesn't rotate with the objects, but in fact no longer bounds the objects. I can't figure out why this is.
Please let me know if there's a better way to do this, and/or what my bone-headed error is in the above code that keeps the computed bounding boxes from rotating with the objects.