# Position an object at the center of the screen

I need to create a grid of squares such as the grid is centered on the screen. Here is a schema:

I need the two green lengths to be equal, and the two red lengths to be equal.

Here is the method I am using right now to try to generate this pattern (slotGrid is a 2D array, but only its size is revelant right now).

void GenerateLevel(bool[,] slotGrid) {

// The size of the grid, in the image above this is equal to 2 as it is a 2*2 grid
// Note that I assume that the grid width and height are equal
int slotGridSize = slotGrid.GetLength(0);

// The size of one of the square
float slotSizePixel = m_Slot.transform.lossyScale.x;

// The size of the screen
float screenWidthPixel = Screen.width;
float screenHeightPixel = Screen.height;
Debug.Log("Screen size: " + screenWidthPixel + "*" + screenHeightPixel);

// Position of the upper left square
float firstSlotX = (screenWidthPixel - (slotGridSize*slotSizePixel)) / 2;
float firstSlotY = (screenHeightPixel - (slotGridSize*slotSizePixel)) / 2;
Debug.Log("First slot position: " + firstSlotX + "," + firstSlotY);

Vector3 newSlotPosition = new Vector3(firstSlotX, firstSlotY, 0);

// Generate the grid starting from upper left corner
for (int i = 0; i < slotGridSize; i++) {
for (int j = 0; j < slotGridSize; j++) {
Instantiate(m_Slot, newSlotPosition, Quaternion.identity);
newSlotPosition = new Vector3(newSlotPosition.x + slotSizePixel,
newSlotPosition.y,
0);
}
newSlotPosition = new Vector3(firstSlotX, newSlotPosition.y, 0);
}
}


However, this method is placing the squares in some weird position (i.e far off the screen). I realized this is because I mix pixel size (for the screen width and height) and... Unity scale size I guess (I don't know the proper name) for the square size.

How can I fix this?

• Side note: I would refer to “Unity scale size” as “Unity units” or perhaps “World space coordinates” – Ed Marty Jul 29 '18 at 13:42
• Note that the Length property of a multidimensional array is the total number of elements in the array. You should use slotGrid.GetLength(0) instead to get the size of the first dimension of the array (before the comma). – Ed Marty Jul 29 '18 at 13:52