Position an object at the center of the screen

by Eldy   Last Updated July 29, 2018 13:13 PM

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

enter image description here

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.Length;

    // 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 = 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?

Related Questions

UI position different

Updated April 22, 2017 21:13 PM

Unity C# Object Scaling when parenting by script

Updated June 17, 2015 00:05 AM

Help with transform.lookat and camera?

Updated July 27, 2017 01:13 AM

(unity) move the world or the character

Updated December 06, 2018 22:13 PM