How do I get the bounds of a rigidbody's compound collider?

How do I get the bounds of a rigidbody’s compound collider?

I’ve looked through the Unity documentation and googled looking for the answer and couldn’t find anything about this. If I need something like that, would most people just grab the bounds from “renderer.bounds”?

Thanks!

edit: I just realized this post may be in the wrong catagory, not sure though. Should I have asked this in Unity Answers? Or the scripting forum? Whoops, sorry!

Loop through the children and get their bounds, and add them all together.

–Eric

Thanks! ‘Adding’ might not have been the most accurate word. I first tried adding all the sizes together and realized that was inflating too much (interior colliders extending length). Looking at the documentation, ‘Encapsulate’ is what I needed to do. For anyone needing to do this in the future, the code is something like:

		Collider[] myColliders = GetComponentsInChildren<Collider> ();
		Bounds myBounds = new Bounds (transform.position , Vector3.zero);
		foreach (Collider nextCollider in myColliders)
		{
			myBounds.Encapsulate (nextCollider.bounds);
		}
		Debug.Log (myBounds);

The myBounds variable is printing out nicely to the console, and changing the rotation of the parent is increasing/decreasing the size of the AABB! Woot! :slight_smile:

2 Likes

Indeed, Bounds.Encapsulate is what I was referring to; sorry for not being more specific. Glad you found it anyway. :slight_smile:

–Eric

Since this answer is still valid 7 years later, I wanted to correct something:

If your colliders do not encapsulate the transform.position of your rigidbody, the solution above will not give the correct results. Here’s a utility method that works even in that case:

      public static Bounds GetCombinedBoundingBoxOfChildren(Transform root)
        {
            if (root == null)
            {
                throw new ArgumentException("The supplied transform was null");
            }

            var colliders = root.GetComponentsInChildren<Collider>();
            if (colliders.Length == 0)
            {
                throw new ArgumentException("The supplied transform " + root?.name + " does not have any children with colliders");
            }

            Bounds totalBBox = colliders[0].bounds;
            foreach (var collider in colliders)
            {
                totalBBox.Encapsulate(collider.bounds);
            }
            return totalBBox;
        }
3 Likes