Skip to main content
1 of 5

I wrote a quick sample, the grid is always centered to the spawn position. You can adjust the following:

  • number of objects in x and y direction, just like you already had it
  • distance between objects in x and y direction (seperately)
  • assign a transform which provides the spawn position, if it's null, the grid will stay at the world origin

Looks a bit confusing, but just to get an idea...

using UnityEngine;
using System.Collections.Generic;

public class GridManager : MonoBehaviour
{
    public int GridWidth;
    public int GridHeight;
    public int distanceX;
    public int distanceY;
    public Transform spawnPoint;
    public GameObject myPrefab;
    public List<GameObject> list = new List<GameObject>();

    void Start()
    {
        CreateGrid();
    }

    public void CreateGrid()
    {
        GameObject newEmptyGameObject = new GameObject("Grid");
        // following line is probably not neccessary
        newEmptyGameObject.transform.position = Vector3.zero;

        // some math to find the most left and bottom offset
        float offsetLeft = (-GridWidth / 2f) * distanceX + distanceX / 2f;
        float offsetBottom = (-GridHeight / 2f) * distanceY + distanceY / 2f;
        // set it as first spawn position (z=1 because you had it in your script)
        Vector3 nextPosition = new Vector3(offsetLeft, offsetBottom, 1f);

        for (int y = 0; y < GridHeight; y++)
        {
            for (int x = 0; x < GridWidth; x++)
            {
                GameObject clone = Instantiate(myPrefab, nextPosition, Quaternion.identity) as GameObject;
                clone.transform.parent = newEmptyGameObject.transform;
                list.Add(clone);
                
                // add x distance
                nextPosition.x += distanceX;
            }
            // reset x position and add y distance
            nextPosition.x = offsetLeft;
            nextPosition.y += distanceY;
        }
        // move the whole grid to the spawnPoint, if there is one
        if (spawnPoint != null)
            newEmptyGameObject.transform.position = spawnPoint.position;
    }
}