Tiles: how to tell what tile asset is at a grid space

What I know:

  • I can check if a tile exists for a particular tile with Tilemap.HasTile(Vector3 pos)
  • I can get a reference to a tile at a position with TileMap.GetTile<Tile>(Vector3 pos)
  • I can check what sprite is on that tile: TileMap.GetTile<Tile>(Vector3 pos).sprite

With the above, I can determine what tile is at a position by checking what sprite is on it. By having a reference to that sprite, I can check for specific interactions I care about (for example, which of two different kinds of power-ups is on this tile).

But checking sprites seems kind of kludge-like. Can’t I just check for one of the specific tiles from my tile assets? I had hoped I could use Tilemap.GetTile<Tile>(Vector3 pos).GetType() to see what tile is at that location - but that just returns “Tile”.

Checking Tilemap.GetTile<Tile>(Vector3 pos).name gives me the name of the tile asset - but that’s a string, and generally I’ve been taught to avoid using string comparison as it’s slow/klunky.

So: given a list of tile assets, how can I check if they exist at a particular place in a tilemap? Is there a better way?

Comparing the Tile asset references will work, such as determining if the Tile asset at the position on the Tilemap is in your list of Tile assets:

var tilemapTile = tilemap.GetTile(pos);
int i = 0;
for (; i < tileList.Count; ++i)
{
    if (tilemapTile == tileList[i])
        break;
}
if (i < tileList.Count)
{
    // Do something with matched Tile
}

If you know exactly which Tile asset is your power-up Tile, you could directly compare it:

var tilemapTile = tilemap.GetTile(pos);
if (tilemapTile == powerupTile)
{
    // Do something with matched Tile
}
1 Like

As long as you don’t use it in Update or a thousand times i time in a script, using strings won’t be a problem.

Oh dang. I’m so embarrassed. I had references to the tile all along. I don’t know why I didn’t think of just comparing the actual Tile returned by TileMap.GetTile<Tile>(Vector3 pos) with the tile asset (either by dragging to the inspector or loading the resource).

At any rate, thanks much for the answer - this makes a lot more sense and greatly simplifies identifying animated tiles. I appreciate the thoughtful reply!

Apart from the question of slow or fast…comparing strings is prone to error, for instance, if you decide to rename your sprites and then accordingly the assets you have to find all those names also in code or the comparison will fail without telling you about it.