Bounds of GameObject after scaling

Viewed 166

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);
1 Answers

I know its been a while since this was asked, but here is a solution. if you divide the bounds you calculate in your code by the scale of your object it should fix your issue.

Vector3 assetScale = assetTransform.localScale;
//assetTransform could be this.transform
collider.size = new Vector3(collider.size.x/assetScale.x,collider.size.z/assetScale.y,collider.size.z/assetScale.z);
Related