Get the center of multiple cubes at runtime (not the pivot)
Having a few cubes that all have the same parent, I would like to get the center (not the pivot) of some of them at runtime. As shown below, in the editor when the application is not running it's really easy to get the center of different cubes and visualize it just by selecting cubes with the "Center" mode enabled. The problem is, I couldn't find a way to get this position at runtime. I tried to implement centroid algorithms but there must be some easier ways to get it.
Below is the center of the selected cubes in the editor and the pivot of the cubes parent Below is the position I'm looking for to get at runtime
Answer by Bunny83 · Jan 06, 2019 at 02:40 AM
Yes, the easiest way to get a similar behaviour you see for the center handle mode in the editor is to use the "Bounds" of all cubes and simply "combine" them. Just iterate through your objects, grab the "Renderer" component of each object and read "Renderer.bounds". Initialize a Bounds variable with the first object you want to include. Then just use Encapsulate like this:
Bounds b = firstRenderer.bounds;
foreach(Renderer r in allRenderers)
{
b.Encapsulate(r.bounds);
}
"b" will be the AABB (axis aligned bounding box) that contains all the bounding boxes of the objects you've iterated over. You can simply grab the center of "b" if that's all you want to know.
Works like a charm, thanks! Just had to change b = b.Encapsulate(r.bounds);
to b.Encapsulate(r.bounds);
because Encapsulate doesn't return anything
You're right. I thought ir returns a new bounds but it actually mutates the struct. I'll edit my answer to get it right ^^.