Skip to main content
3 of 3
BoxCollider2D.center has been deprecated. Use BoxCollider2D.offset instead

I found out that the Boxcollider I get from the solution above was only expanding the bounds of all the children while leaving out the gameObject itself aswell as all other descendants, and it only delivered the right solution for position and rotation 0, and scale 1, which confused me at first.

here is the code that will surround the gameobject and every descendant: (keep in mind that you need to set the position and the rotation to 0 and the localScale to 1 and to get the right Collider. Just store the old transform variables somewhere and then set them to 0 (and scale to 1) , then change the collider (call this script), then set the transform variables back again) . Have fun!

public void addBoundsToAllChildren()
{
    if (boxCol == null)
    {
        boxCol = gameObject.GetComponent(typeof(BoxCollider)) as BoxCollider;
        if (boxCol == null)
        {
            boxCol = gameObject.AddComponent<BoxCollider>();
        }
    }
    Bounds bounds = new Bounds(Vector3.zero, Vector3.zero);
    Renderer thisRenderer = transform.GetComponent<Renderer>();
    bounds.Encapsulate(thisRenderer.bounds);
    boxCol.offset = bounds.center - transform.position;
    boxCol.size = bounds.size;

    allDescendants = gameObject.GetComponentsInChildren<Transform>();
    foreach (Transform desc in allDescendants)
    {
        Renderer childRenderer = desc.GetComponent<Renderer>();
        if (childRenderer != null)
        {
           bounds.Encapsulate(childRenderer.bounds);
        }
        boxCol.offset = bounds.center - transform.position;
        boxCol.size = bounds.size;
    }
}
OC_RaizW
  • 1.5k
  • 8
  • 27
  • 49