Use Unity Tilemap to make 2D class maps

For some 2D games, the production and use of maps may be a difficult task. Unit also provides some good interfaces and API s to meet these requirements. This article introduces the use of Tilemap components and other components to realize the simple production and use of this kind of map.

1, Component introduction

To make a map, you need the cooperation of Grid, Tilemap and tilemapprender. The following is a brief introduction to these three components:
1,Grid (Official website address)
The Grid component converts the Grid cell position into the corresponding local coordinates of the game object.

cell Size: the size of each cell
cell Gap: cell Gap
cell Layout: the shape and arrangement of cells
cell swizzle: cell coordinate conversion order

2,Tilemap(Official website address)
Tilemap component is used to store and process the displayed image resources, and render the required information through tilemapper.

Animation Frame Rate: the rate at which animation plays
Color: picture color
Tile Anchor: the anchor offset of the picture
Orientation: on which plane is the map displayed

3,Tilemap RendererOfficial website address
The Tilemap Renderer component (similar to the Sprite Renderer component) is part of Tilemap and determines the rendering method of the image.

Sort Order: sets the sort direction of the map
Mode: sets the map rendering mode
Detect chunk culling boundaries: Mask culling boundaries
Chunk culling boundaries: value of culling boundaries
Mask Interaction: Mask relationship

2, Scene construction

First, create a new GameObject in the scene, name it Grid (you can name it according to your own situation), and add the Grid component; Then add a sub object GameObject to the Grid, named Tilemap, and add Tilemap component and Tilemap Renderer component. As shown in the figure:


Different requirements have different settings for corresponding components. Readers can set the corresponding display mode according to their own needs.

3, Edit map

First, find the 2D Tilemap Editor in Window - > package manager and install it:

After installation, find the TilePalette in Window - > 2D, open it, create a new palette, and then drag the material of a map into the small square to store the material pictures of your own map in the new gallery.

In the Tile Palette panel, the top operation tools are: select, move, brush, simultaneous operation of multiple materials, straw, eraser and fill. Use these tools to draw the map you want.

4, Exporting and loading maps

First, create a GridManager script. The following is part of the code responsible for loading the map:
(of course, we must have the data of the existing map when loading the map)

for (int i = 0; i < map.w; i++)
  {
      for (int j = 0; j < map.h; j++)
      {
          //Setting of precast body
          cellTile.color = Color.white;
          cellTile.sprite = singleSprite;

          //Set cell data
          tilemap.SetTile(new Vector3Int(i, j, 0), cellTile);
      }
  }
  //Refresh the entire map
  tilemap.RefreshAllTiles();

The following is the style of the loaded map (10 * 10):

When exporting a map, I use binary serialization and deserialization. The code is as follows:

/// <summary>
    ///Simple use of binary serialized data
    /// </summary>
    /// <param name="path"></param>
    private void BinarySerilizeMap(string path) 
    {
        var data = new MapData
        {
            w = width,
            h = height,
        };

        FileStream fs = new FileStream(path, FileMode.Create, FileAccess.Write);

        BinaryFormatter bf = new BinaryFormatter();

        bf.Serialize(fs,data);

        fs.Close();

        Debug.Log("Storage successful");
    }


    /// <summary>
    ///Deserialize data
    /// </summary>
    /// <returns></returns>
    private MapData BinaryDeSerilizeMap() 
    {
        if (!File.Exists(savePath))
        {
            //file does not exist
            Debug.Log("Save a map before loading: press the spacebar to store a default map");
            return null;
        }

        FileStream fs = new FileStream(savePath, FileMode.Open, FileAccess.Read);
        BinaryFormatter bf = new BinaryFormatter();
        var data = (MapData)bf.Deserialize(fs);
        fs.Close();
        return data;
    }

Readers can write their own unique encryption and decryption methods according to their own needs.

4, Introduction to common API s

The following API s are commonly used in making map composition:

ClearAllTiles() Clear all cell data
GetCellCenterLocal() Gets the local coordinates of each cell
GetCellCenterWorld() Gets the world coordinates of each cell
GetSprite(Vector3Int position)  Get picture information at the specified location  
GetTile() Gets information about the cell at the specified location
RefreshAllTiles() Refresh the entire map
RefreshTile(Vector3Int position) Refreshes the cell at the specified location
SetTile()  Set cell data at the specified location
SetTiles(Vector3Int[] positionArray, TileBase[] tileArray) Directly use the array to set multiple pictures in multiple positions

5, End

The above is my summary in the process of operation. I wrote an article for the first time. If there are any mistakes, please leave a message and point out that you can also leave a message if you encounter any doubts in the process of reading. The project scene has also been uploaded. You can search and download it for free!!!

Tags: html C# Unity

Posted by Atiq on Wed, 22 Sep 2021 22:08:19 +0530