0

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.

Soviut
  • 88,194
  • 49
  • 192
  • 260
ParagonTime
  • 145
  • 1
  • 10

1 Answers1

1

The issue is that you're using a < less than, so once it actually hits the tileHeight it exits the loop one iteration too early. Make it <=.

Soviut
  • 88,194
  • 49
  • 192
  • 260
  • that solved the first issue so upvote and answer for that but what about the lone tile being spawned at 0,0? – ParagonTime Aug 08 '16 at 18:10
  • There's a good chance it's unrelated. Check that your scene doesn't contain the original prefab. Also check that you don't have test code spawning an instance anywhere. – Soviut Aug 08 '16 at 18:13