I'm writing a code in order to calculate the gameObject's box collider. When I use the method GetBounds() without scaling the object, the method work perfectly. Instead, if I scale the object (with localScale) and then launch GetBounds() method, the box collider appears very small. Thank you in adavance for anysuggestions.
This is the code I use:
bool boxC = false;
BoxCollider collider;
Bounds bounds = new Bounds();
bounds.size = Vector3.zero;
bounds.center = Vector3.zero;
Renderer[] renderers = this.GetComponentsInChildren<Renderer>();
bool hasBounds = false;
if (renderers.Length > 0)
{
foreach (Renderer renderer in renderers)
{
if (renderer != null)
{
if (hasBounds)
{
bounds.Encapsulate(renderer.bounds);
}
else
{
bounds = renderer.bounds;
hasBounds = true;
}
}
}
}
if (this.GetComponent<BoxCollider>() == null)
this.gameObject.AddComponent<BoxCollider>();
collider = this.GetComponent<BoxCollider>();
collider.center = bounds.center - this.transform.position;
collider.size = bounds.size;
collider.center = new Vector3(collider.center.x, collider.center.y, 0);