Having some issues with procedurally generating a map

I’m building a very simple 2d tile map. It just spawns a few different grass tiles in random locations here’s what it looks like:

public int tileHeight; //y 
	public int tileWidth; //x 
	int tileHeightCounter;
	int tileWidthCounter;

	public GameObject[] floorTiles; 





	void Start(){
		 
		tileHeightCounter = 0; 
		tileWidthCounter = 0; 

		while(tileHeightCounter < tileHeight){ 

			Vector3 tileSpawnPoint = new Vector3 (tileWidthCounter, tileHeightCounter, 0); 

			GameObject groundTiles = (GameObject)Instantiate (floorTiles[Random.Range(0, floorTiles.Length)], tileSpawnPoint, Quaternion.identity); 
			groundTiles.transform.parent = transform; 




				
				if (tileWidthCounter == tileWidth) {
					tileWidthCounter = 0;
					tileHeightCounter++;
			}

			tileWidthCounter++;

		}



	
	}

I’ve run into two problems-
say your tileHeight is 10 and your tileWidth is also 10 then the map it generates should be a 10x10 with 100 total tiles randomly distributed.

Instead two weird things are occurring the first is that if your map is 10x10 it actually generates a 10x9 meaning it stops one layer short on the y axis.
The second is a grid(grass tile) is being created at 0,0 but the rest of the map is being created with at least x being 1 meaning that the map has a single tile attached to the bottom left sticking out.

I’m a bit confused as to whats going on here or how to fix it.
Any help is much appreciated.

it would be way easier and prettier if you used two nested for-loops like this:
public int tileHeight;
public int tileWidth;

    public GameObject[] floorTiles;

    void Start()
    {
        for(int x = 0; x < tileWidth; x++)
        {
            for(int y = 0; y < tileHeight; y++)
            {
                Vector3 tileSpawnPoint = new Vector3(x, y, 0);

                var groundTiles = (GameObject)Instantiate(floorTiles[Random.Range(0, floorTiles.Length)], tileSpawnPoint, Quaternion.identity);
                groundTiles.transform.SetParent(transform, true); //2nd parameter makes sure the tile stays at its global position
            }
        }
    }

In the code you posted, the loop runs once more than you want for each row, meaning that the tile field will be one tile too large in the width everytime, while being correctly sized in the y direction… so theoretically your code would produce a 11x10 field if I’m correct :slight_smile: