Adjust Orthographic Camera to fit object

I am using an Orthographic Camera to take picture of dynamically generated objects. The object could very in size from very small to very large. I need to move my camera so it is directly over the object and pointing straight down (I can do this easily) and I need to adjust the size and/or viewport rectangle so that it just barely fits the object – this is where I am struggling.

So I am looking for a math needed to adjust the size and/or rect so that the camera fits. Bonus point if you can provide the c# code, but I can figure all that out - really I just need the math.

For the Orthographic Camera the size is the number of unity units from the center of the camera to the top/bottom of the screen. The width is then based on the aspect ratio. So if you know how big the objects are that should be easy!

You can get or set the main camera size with Camera.main.orthographicSize

then get/set the aspect ratio (width/height) with Camera.main.aspect

and you can reset it after with Camera.main.ResetAspect();

Hope that helps!

You can add a zoom fit all functionality by using Unity Bounds and the camera position and orthographic size.
I have made the video below that shows how to use Unity script to zoom fit a model to the screen even when the model is consist of multiple meshes.

Zoom Fit All Camera in Unity Script