2

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);
Zaki
  • 21
  • 1
  • Is it possible that the bounds appear too small because it's very far away? Can you Debug.Log the bounds' size and center values and verify that it shrinks? P.S. Forgot to mention that BoxCollider's size is in local space. So you'd have to divide its size by transform.localScale. – yasirkula Sep 27 '21 at 19:48

1 Answers1

0

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);
Ben
  • 1
  • 1