How to place tiles on Unity by script?

How can I set and remove a tile on a tilemap on Unity using a C# script?

Asked by blademan @

Blademaster Answer

TLDR; use the SetTile method. Passing a null as the tile parameter will remove the tile from the map.

To do that you need a reference of the tilemap you want to control on your C# script. You also will typically need a tile reference. Then, call the method SetTile passing the position on the grid and a tile.

public class MapController : MonoBehaviour {

    public Tilemap map;
    public Tile tile;

    // note that i and j are cell positions
    // the bottom left is the origin (0, 0)
    void ChangeMap(int i, int j) {
        map.SetTile(new Vector3Int(i, j, 0), tile);
    }

}

Some other pretty useful methods are:

  • WorldToCell: converts a world position to a cell position (Vector3Int).
  • BoxFill: an optimized version of SetTile, use it whenever you can.
  • FloodFill: does a flood fill. A flood fill is the algorithm behind bucket tools of lots of painting software. See more at wikipedia.
© Bladecast 2018. All rights reserved.