Pathfinding on tilemaps

This page describes how to get pathfinding working using Unity's tilemaps.

Tilemaps are a versatile tool for making 2D games in Unity. They allow you to easily and efficiently render sprites in a grid pattern, or even other regular patterns like hexagonal grids.

When using a tilemap, it is recommended to use either a grid graph (not the layered kind) or a recast graph.

Tilemaps and Grid Graph

Using a tilemap with a grid graph is pretty simple. If you create a tilemap in your scene, this tilemap will show up in the grid graph's inspector to allow you to align the grid to the tilemap. This is very useful, as matching the settings by hand can sometimes involve a lot of trigonometry. This also works for more exotic shapes like hexagonal grids.

Sometimes you do not want a 1 to 1 correspondance between tiles and grid cells, though. For example you can use 3 grid cells per tile to allow for more fine-grained movement. You can achieve this by first aligning the grid to the tilemap as shown above, and then adjusting the node size to one third of its original value, or whatever works best for your game.

Since tilemaps use 2D physics, you will also want to enable the "use 2D physics" checkbox.

Use 2D Physics

Use Unity 2D Physics API.

If you use a CompositeCollider2D on your tilemap, you must ensure that it is set to Geometry Type = Polygons. If it is set to Outlines, then the collider may not be properly detected by the grid graph.

Tilemaps and Recast Graph

Using a tilemap with a recast graph is also pretty simple. First you must change the graph to 2D mode by changing the dimensions setting to 2D.

Dimensions

Whether to use 3D or 2D mode.

Then, ensure that the tilemap has a TilemapCollider2D attached, that rasterize colliders is enabled in the recast graph settings, and finally that the tilemap's layer is included in the rasterization layer mask in the recast graph settings.

You can adjust the cell size to get more or less detailed graphs.

Graph Updates

If you update your tilemap at runtime, you may want to update the graph as well. This can be done by calling AstarPath.UpdateGraphs with the bounds of the part of the tilemap that you modified. It works the same way as when updating a graph with a normal collider.

If you've made changes to pretty much the whole map, you can call AstarPath.active.Scan() to recalculate the whole graph.