Making a grid-based background

Dear Unity users,

I am currently working on my second Unity project. I am trying to make a tile-based background image, meaning that I want to place tiles next to each other in a grid to form a full background image. So I wrote a method which basically places my tiles in a grid

for (int y = 0; y < level.Height; ++y)
      for (int x = 0; x < level.Width; ++x)
            {
               int xPos = x * this.tileWidth;
               int yPos = y * this.tileHeight;
               AddTile(xPos, yPos, "Background/Wall");
             }

The tileWidth and Height in this case are equal to the tile image width and height in pixels.

What I want it to do is to place the tiles nicely in a grid exactly next to each other. But something fishy is going on with the coordinates in the Unity system. When I run my code without any modifications this is what I get:


a bit closer:

So ok, pixel coordinates and actual world coordinates aren’t the same. That is clear. At this point I started to look for methods that could transform the world coordinates to pixel coordinates and I stumbled upon Camera.ScreenToWorldPoint() which supposedly returned the coordinates I wanted. But when I applied that method this is what came out:


Looks pretty good right? The tiles are nicely in a grid without any gaps inbetween. But wait…

Apparantly, tiles still overlap and aren’t perfectly placed next to each other in a grid.

So now my question, how can I place my tiles nicely in a grid using pixel coordinates?

Ok, so I found the solution to my problem. I had to use the SpriteRenderer.bounds.size.x command to get the size of the texture I used in the Unity world. Using that as my tileWidth and tileHeight placed the tiles exactly at the right positions.