This is an older post, but I had a similar need, and I ran into some problems due to several got-yas
For the first time, I noticed that my calculated parent box was wider than it should, and that it was not completely centered.
The reason was that my objects had a turn applied to them and the restrictions were never enforced; therefore, before performing my calculations, I first had to turn back to zero; then after the calculation, I was able to restore the original rotation.
In my case, not all of my child objects had renderers, in addition, my children could have children from them, so I do not want to calculate the center when transforming children. I wanted child components to display components.
Below is the code I came across; heavy comments; not optimized, but does the trick, takes into account grandchildren, if you will and process objects with the start of rotation.
//Store our current rotation Vector3 LocalAngle = transform.localEulerAngles; //Zero the rotation before we calculate as bounds are never rotated transform.localEulerAngles = Vector3.zero; //Establish a default center location Vector3 center = Vector3.zero; //Establish a default empty bound occupiedSpace = new Bounds (Vector3.zero, Vector3.zero); //Count the children with renderers int count = 0; //We only count childrent with renderers which should be fine as the bounds center is global space foreach (Renderer render in transform.GetComponentsInChildren<Renderer>()) { center += render.bounds.center; count++; } //Return the average center assuming we have any renderers if(count > 0) center /= count; //Update the parent bound accordingly occupiedSpace.center = center; //Again for each and only after updating the center expand via encapsulate foreach (Renderer render in transform.GetComponentsInChildren<Renderer>()) { occupiedSpace.Encapsulate(render.bounds); } //In by case I want to update the parents box collider so first I need to bring things into local space occupiedSpace.center -= transform.position; boxCollider.center = occupiedSpace.center; boxCollider.size = occupiedSpace.size; //Restore our original rotation transform.localEulerAngles = LocalAngle;
source share