# Keeping instantiated grid in the centre of the screen?

everyone, I'm making a mobile game and I need help. In the game, I instantiate a grid of dots as seen in the first attached file below. My problem is the grid is not in the centre of the screen I could just position my main camera so the grid is in the centre the only problem with this approach being that the grid changes in size depending on your level as shown in attachment 2

here's my spawn code

  for (int x = 0; x < gridX; x++)
{
for (int y = 0; y < gridY; y++)
{
SpawnDelay = Random.Range(0.2f, 0.5f);
yield return new WaitForSeconds(SpawnDelay);
Instantiate(Dot, transform.position, transform.rotation);

NumberOfdots++;
transform.position = new Vector2(transform.position.x + distanceBetween, transform.position.y);
if (y % MutpleNum == ByMutpleNum)
{
transform.position = new Vector2(GridoffsetX/2, transform.position.y + GridoffsetY);
}
}

}


Is there anyway I can have the grid centre regardless of its size

Thanks,

David

1. Determine the width, height, and the coordinates of the corner of the rectangle in which you want the dots to appear. How to do this depends on how large you want the border to be and on the settings and position of your camera.
2. Divide width by the horizontal number of dots. This is your x-increment.
3. Divide height by the vertical number of dots. This is your y-increment.
4. Determine the instancing position by multiplying the increment with the loop-counter and then add the start position and half the width (to get it neatly centered).

Here is an example script. The script uses the orthorgaphic size of the main camera as the desired size of the rectangle, which is half the vertical screen size:

public class GridCreator : MonoBehaviour {

public GameObject dotPrefab;
public int numRows;
public int numColumns;

// Use this for initialization
void Start () {

Camera camera = Camera.main;

// determine the size of the whole rectangle
float rectWidth = camera.orthographicSize;
float rectHeight = camera.orthographicSize;
float rectX = camera.transform.position.x - rectWidth / 2.0f;
float rectY = camera.transform.position.y - rectHeight / 2.0f;

// fill the rectangle with dots
float xDistance = rectWidth / numColumns;
float yDistance = rectHeight / numRows;

for (int x = 0; x < numColumns; x++) {
for (int y = 0; y < numRows; y++) {

Vector2 position = new Vector2( x * xDistance + rectX + xDistance / 2.0f,
y * yDistance + rectY + yDistance / 2.0f);

Instantiate(dotPrefab, position, Quaternion.identity);
}
}
}
}


You could optimize this code slightly by avoiding the + xDistance / 2.0f part in the position calculation by add that offset to rectX instead, but in my opinion this makes the code harder to follow. And considering that this isn't performance-sensitive code, I would rather go for the clearer solution.

I'm looking forward to playing your game.