I have a GameObject “Master”. Master has multiple children. Now I want to create a bounding box around Master that encapsulates all children. This is easily done with this code…
var grpBounds = new Bounds() { center = master.transform.position };
foreach (var meshrenderer in master.transform.GetComponentsInChildren<MeshRenderer>())
{
grpBounds.Encapsulate(meshrenderer.bounds);
}
boundingbox.localScale = grpBounds.size;
boundingbox.position = grpBounds.center;
… The problem is that “Encapsultate()” draws bounds in global space. The previous code works fine, as long Master is aligned with global space. But if Master is rotated, the boudns will be still aligned with global space making the boundingbox way to big.
One solution for this is to align master globally, while bounds are calculated and then rotate everything back, with the bounds as child of master. This is a very awful solution though, and I’m sure there is a better one somewhere
Nonetheless, as per the docs, the bounds do not rotate with the object. They encapsulate the object on the global axis, expanding if the rotated object would be larger than were it not rotated.
Well using Unity’s bounds won’t work here in that case. You would probably need to define your own bounds - or perhaps size - per-object, and accumulate those values to produce a box of the right size, and then rotate that based on the root object.
Unless these objects are not dynamically changing, in which, just define your own size that encompasses everything and use that.