Center of a GameObject with Bounds?

I’m trying to find the center of a GameObject using the renderer bounds. Some of my GameObjects have a renderer on the parent where the script is attached, while others are grouped under an empty GameObject, so I need a method that accounts for both.

I am using the following code to try and add all the renderers of the children to a single object, then get the center point of the combined bounding box.

    protected Bounds _combinedBounds;
    protected Renderer _renderer;

    void Awake(){
        _renderer = GetComponent<Renderer>();

        if (_renderer){
            _combinedBounds = _renderer.bounds;
        }

        else{
            _combinedBounds = new Bounds();
        }
        
        Renderer[] renderers = gameObject.GetComponentsInChildren<Renderer>();

        if (renderers.Length > 0){
            for (int i = 0, len = renderers.Length; i < len; i++){
                _combinedBounds.Encapsulate(renderers*.bounds);*

}
}
*Debug.DrawLine(_combinedBounds.center, new Vector3(0,50,0)); *

  • }*
    Below you can see that I’ve added the script to two separate GameObjects. You can also see that the results are way off center. Further, if I try to move the objects from those points, the bounds get even more off-center.
    [69450-not-correct.png|69450]*

It seems like the farther I go from the center, the more off everything becomes. Does anyone know what I can do to get the center point of an object painlessly?

AH HA!
That last pic and notes had the key piece of information need to spot the bug: The fact that (0,0,0) was always included in the bounds.

The REASON this happens is: according to you code, if the root object does not have a renderer, you start the bounds off with:

_combinedBounds = new Bounds();

This will create a new bounds object, with min, max, center of (0,0,0).
When you call Encapsulate- you are extending the bounds to include the new boundaries, but this does NOT REMOVE the original bounds you started with, they are joined together.
So, you newly encapsulated bounds will ALSO include (0,0,0).

To eliminate this error, do NOT initialize the bounds with new Bounds(), instead wait until you have an actual render object with bounds, and THEN start combining.