0
\$\begingroup\$

How do I generate a 2D tile map from an array like in this tutorial for XNA ? I basicly want to generate a static map based on my tile prefabs.

\$\endgroup\$
1
\$\begingroup\$

Its actually very similar to the way it is done in XNA , only a few changes in the syntax and loading approach.

Here is the most basic way in which it can be done. You can build on top of it as per your needs.

Before we start, we need to make some tile prefabs and store it inside the resources folder.

enter image description here

Lets define some variables, and initialise them some default values.

    //Your Tile Map
    public int[,] tileMap = new int[,]
    {
     {0,1,2},
     {1,1,0},
     {2,2,2}
    };

    public float TileSize;
    public Vector2 StartPoint;//top left corner of the map

    // Use this for initialization
    void Start () 
    {
        TileSize = 1;
        StartPoint = new Vector2 (1, 1);
        PopulateTileMap ();
    }

The StartPoint is the top left corner of the map. So you can define from where it should start populating on the screen.

Now lets look at the core logic behind populating the tiles , as per our tilemap.

public void PopulateTileMap ()
{
    for(int i = 0 ; i < 3 ; i ++)
    {
        for(int j = 0 ; j < 3 ; j ++)
        {

            GameObject prefab = Resources.Load ("tile_"+tileMap[i,j].ToString()) as GameObject;
            GameObject tile = Instantiate(prefab, Vector3.zero, Quaternion.identity ) as GameObject;
            tile.transform.position = new Vector3(StartPoint.x + ( TileSize * i ) + ( TileSize/2) , StartPoint.y + (TileSize * j ) + ( TileSize/2), 0);

        }
    }
} 

Here we instantiate the prefabs from our resources folder. The name is created as per the tile map we have defined earlier. For position, adding the tile size to the starting point will give the top left corner of the individual tile. But as our pivot is in centre we add an extra offset of (TileSize/2).

Hope this resolves your doubt :)

| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

I think you will have a very similar stuff, compared to this tutorial. You will instantiate prefabs in each tile position. I would create prefabs of tiles based on functionality: Ground Tile Prefab, WaterTile Prefab, etc. Each one with options to activate/deactivate game Objects, to change the looking, for example. You rather use something with a little bit more information than a simple array of ids. I would recommend you to check it out: http://www.mapeditor.org/

There is some Unity projects on github integrating with the mapeditor, and you can use it as examples.

| improve this answer | |
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.