How to convert a BoxCollider2D bounds to world space?

A BoxCollider2D has members called size and center, and these are supposedly in “local” coordinates. Is there an easy way to convert this to world coordinates, or even better, a way to get the world bounds Rect of a BoxCollider2D directly?

I couldn’t find a super-easy way, but I created this extension method for BoxCollider2D which accomplishes the task:

public static Rect GetWorldBounds(this BoxCollider2D boxCollider2D)
{
    float worldRight = boxCollider2D.transform.TransformPoint(boxCollider2D.center + new Vector2(boxCollider2D.size.x * 0.5f, 0)).x;
    float worldLeft = boxCollider2D.transform.TransformPoint(boxCollider2D.center - new Vector2(boxCollider2D.size.x * 0.5f, 0)).x;

    float worldTop = boxCollider2D.transform.TransformPoint(boxCollider2D.center + new Vector2(0, boxCollider2D.size.y * 0.5f)).y;
    float worldBottom = boxCollider2D.transform.TransformPoint(boxCollider2D.center - new Vector2(0, boxCollider2D.size.y * 0.5f)).y;

    return new Rect(
        worldLeft,
        worldBottom,
        worldRight - worldLeft,
        worldTop - worldBottom
        );
}

I haven’t thoroughly tested it yet, but here’s a 3D version that you could modify to work for 2D:

// transform
public static Bounds TransformBounds(this Transform self, Bounds bounds)
{
	var center = self.TransformPoint(bounds.center);
	var points = bounds.GetCorners();

	var result = new Bounds(center, Vector3.zero);
	foreach (var point in points)
		result.Encapsulate(self.TransformPoint(point));
	return result;
}
public static Bounds InverseTransformBounds(this Transform self, Bounds bounds)
{
	var center = self.InverseTransformPoint(bounds.center);
	var points = bounds.GetCorners();

	var result = new Bounds(center, Vector3.zero);
	foreach (var point in points)
		result.Encapsulate(self.InverseTransformPoint(point));
	return result;
}

// bounds
public static List<Vector3> GetCorners(this Bounds obj, bool includePosition = true)
{
	var result = new List<Vector3>();
	for (int x = -1; x <= 1; x += 2)
		for (int y = -1; y <= 1; y += 2)
			for (int z = -1; z <= 1; z += 2)
				result.Add((includePosition ? obj.center : Vector3.zero) + (obj.size / 2).Times(new Vector3(x, y, z)));
	return result;
}

You then can use it as follows:

var worldBounds = transformWithLocalBounds.TransformBounds(localBounds);