I wrote a script that generates a permeability matrix from Tilemap (it searches for an object with TilemapRenderer and TilemapCollider2D, passes through each cell, and if there is a tile, then this information is entered into the permeability matrix).

The script works fine if TieMap is on stage. But I have a lot of such objects in the project folder (in the form of prefabs). I wanted, using the context menu, to call the written function and initialize all prefabs with the appropriate matrices. However, the code written to get the tiles does not work if the object is not on the stage.

Here is this piece of code:

Vector3 worldPos = transform.position // позиция ΠΎΠ±ΡŠΠ΅ΠΊΡ‚Π° с TileMap Π½Π° сцСнС + new Vector3(col, row) * MapBlock.BLOCK_SCALE; // ΠΏΠΎΠ»ΠΎΠΆΠ΅Π½ΠΈΠ΅ ΠΊΠ»Π΅Ρ‚ΠΊΠΈ Π²Π½ΡƒΡ‚Ρ€ΠΈ ΠΎΠ±ΡŠΠ΅ΠΊΡ‚Π° с TileMap var tile = tilemap.GetTile(tilemap.WorldToCell(worldPos)); if (tile != null) block.CellRows[row].Row[col] = true; 

In general, as I understand it, the world coordinates obtained are not correct for an object that is not on the scene.
Then how do i get tiles? How do I need to calculate the coordinates of the tiles and pass them to the tilemap.GetTile() method?

ps tilemap.LocalToCell() I tried.

    1 answer 1

    In general, it was necessary to transfer cell indexes directly.

     var tile = tilemap.GetTile( new Vector3Int(col - MapBlock.BLOCK_SIZE / 2, row - MapBlock.BLOCK_SIZE / 2, 0) ); 

    MapBlock.BLOCK_SIZE - TileMap grid size

    Of course, I had to suffer, until I understood how the cells are located according to their indices ....

    For 2D, the index for Z must be set to 0