Search Unity

  1. Unity Asset Manager is now available in public beta. Try it out now and join the conversation here in the forums.
    Dismiss Notice

TileMap.ContainsTile

Discussion in '2D Experimental Preview' started by Jay-Pavlina, Jun 16, 2016.

  1. Jay-Pavlina

    Jay-Pavlina

    Joined:
    Feb 19, 2012
    Posts:
    195
    I think a useful addition to the TileMap API would be ContainsTile. Here is the use case...

    In my game, there are "themes" for each level. Each theme uses different sets of tiles. I like to be able to switch themes in the editor to see how a level would look with different themes. I use TileMap.SwapTile for this. However, if working in the editor, TileMap.SwapTile is potentially dangerous. If I accidentally swap to a tile that is already in the tile map, I could lose data.

    Here's some pseudo code:

    Code (CSharp):
    1. void SwapThemes(Theme oldTheme, Theme newTheme) {
    2.     for (int i = 0; i < newTheme.tiles.Length; i++) {
    3.         var newTile = newTheme.tiles[i];
    4.         Assert.IsFalse(tileMap.Contains(newTile), "Tile map already contains tiles from that theme!");
    5.         tileMap.SwapTile(oldTheme.tiles[i], newTile);
    6.     }
    7. }
    I know I can do it with an extension method but it won't be very performant since I will have to iterate through every cell. I thought another similar useful addition could be TileMap.uniqueTiles. It would return an IEnumerable<BaseTile> of all the tiles currently used in the map.

    Edit: Here are the extension methods I wrote.

    Code (CSharp):
    1. public static IEnumerable<BaseTile> Tiles(this TileMap tileMap) {
    2.     var size = tileMap.size;
    3.     for (int y = 0; y < size.y; y++) {
    4.         for (int x = 0; x < size.x; x++) {
    5.             if (tileMap.GetTile(new Vector3Int(x, y, 0)))
    6.                 yield return tileMap.GetTile(new Vector3Int(x, y, 0));
    7.         }
    8.     }
    9. }
    10.  
    11. public static IEnumerable<BaseTile> UniqueTiles(this TileMap tileMap) {
    12.     return tileMap.Tiles().Distinct();
    13. }
    14.  
    15. public static bool ContainsTile(this TileMap tileMap, BaseTile tile) {
    16.     return tileMap.UniqueTiles().Contains(tile);
    17. }
    18.  
    19. public static void SwapTileSafely(this TileMap tileMap, BaseTile oldTile, BaseTile newTile) {
    20.     Assert.IsFalse(tileMap.ContainsTile(newTile), "Swap tile failed. Tile Map " + tileMap.name + " already contains " + newTile.name);
    21.     tileMap.SwapTile(oldTile, newTile);
    22. }
     
    Last edited: Jun 16, 2016
  2. Xelnath

    Xelnath

    Joined:
    Jan 31, 2015
    Posts:
    402
    Is there an API for BaseTile anywhere?
     
  3. Johaness_Reuben

    Johaness_Reuben

    Joined:
    Jan 27, 2016
    Posts:
    253
    Documentation that got downloaded with this build and also the reference guide.