I calculate and draw my object bounds in the following code, but obviously the result is not correct like we can see in the attached image. The extent.z is around 0.5 times of renderer size and gizmo is drawn twice with 2 different size…
private Bounds m_Bounds;
public Bounds MyBounds
{
get
{
return m_Bounds;
}
protected set
{
m_Bounds = value;
}
}
// Calculate bounds in start
public virtual void Start()
{
if (rigidbody)
rigidbody.centerOfMass = Vector3.zero;
Renderer[] renderers = GetComponentsInChildren<Renderer>();
Vector3 center = transform.position;
MyBounds = new Bounds(center, Vector3.one);
int count = renderers.Length;
if (count > 0)
{
Renderer r = renderers[0];
Bounds bounds = r.bounds;
center = bounds.center;
m_Bounds.Encapsulate(bounds);
for (int i = 1; i < count; i++)
{
r = renderers[i];
bounds = r.bounds;
center = (center + bounds.center) * 0.5f;
m_Bounds.Encapsulate(bounds);
}
}
}
// Draw center and bounds :
public void OnDrawGizmosSelected()
{
Vector3 center = MyBounds.center;
Gizmos.DrawWireCube(center, MyBounds.extents);
Gizmos.DrawLine(center + Vector3.forward, center - Vector3.forward);
Gizmos.DrawLine(center + Vector3.up, center - Vector3.up);
Gizmos.DrawLine(center + Vector3.right, center - Vector3.right);
}