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?