Center, move and zoom camera to selected gameObjects

I have a 9x9 grid of gameObjects from the X and Y axis, 81 gameObjects. I want to have all of the gameObjects visible to the camera view. The camera I have is stationary and does not move for the entire game. I found myself constantly adjusting the camera’s view and FOV whenever I add or remove gameObjects to the grid.

private var rows = 9;
private var collumns = 9;
static var blocks : GameObject[,];

function Start() {
	blocks = new GameObject[collumns, rows];
	var i = 0;
	for (var y = 0; y < rows; y++) {
		for (var x = 0; x < collumns; x++) {
			blocks[x,y] = GameObject.CreatePrimitive(PrimitiveType.Cube);
			blocks[x,y].transform.localScale = Vector3(0.9, 0.9, 0.9);
			blocks[x,y].transform.position = Vector3(x,y,0);
			blocks[x,y].name = i.ToString();
			blocks[x,y].tag = 'block';

I use the X and Y position of the gameObjects in the 2D array to make gameObjects easier and efficient to find.

Here’s what I want to accomplish on runtime with the camera:

  • Calculate the center/average position point of all gameObjects to change camera’s position
  • Calculate the camera’s Zoom/“Field of View” for all the gameObjects to fit in the shot, without the camera zoom being too far away.

Off the top of my head. To get the center you need to create a Bounds with the min and max vector of your array of objects. Once you’ve done that you can triangulate using the max distance on the ground (x/z) and the offset of the camera(y)

Vector3 offset = new Vector3(0,10f,0);
camera.transform.position = + offset;
var maxShotDistance = Math.Max(bounds.extends.z, bounds.extends.x):

// adjust FOV