ALH
ALH

Reputation: 85

How to align tile game objects in a grid

How do I align tile game objects to my tilemap grid? I've the following settings:

tileSprite: 
  pixels per unit: 32
Grid (created tilemap gameobject):
  Grid component:
    cell size: 32, 32, 0
  GridController script component:
    tileSprite

In the GridController script:

public class GridController : MonoBehaviour {

    public Sprite tileSprite;

    // Use this for initialization
    void Start () {
        for (int x=0; x<5; x++) {
          for (int y=0; y<5; y++) {
            GameObject tile = new GameObject();
            tile.transform.localPosition = new Vector3(x, y, 0);
            tile.transform.localScale += new Vector3(32, 32, 1);

            SpriteRenderer tile_sr = tile.AddComponent<SpriteRenderer>();
            tile_sr.sprite = tileSprite;
          }
       }
    }
}

I would like it to be placed side by side but it seems like they are only 1 pixel apart. Ie. I would like 1 unit to be equals to 32 pixels.

How do I do this? Thank you so much for your help!

I'm using Unity 2017.3.1f1.

Upvotes: 1

Views: 802

Answers (1)

Stejin
Stejin

Reputation: 64

Just by looking at your code:

tile.transform.localPosition = new Vector3(x, y, 0);

You used the loop's variables directly, but you need to calculate the place where the tile is placed. e.g.(might not be fully correct):

tile.transform.localPosition = new Vector3(x*32, y*32, 0);

Upvotes: 1

Related Questions