I have just started getting used to using Unity's new tilemap tool (UnityEngine.Tilemaps).
One issue I am having is that I don't know how to get the x,y coordinates of a placed tile via script. I am trying to move a scriptableObject on the tilemap in script to a new location that the player clicks, but I don't know how to get the coordinates of the clicked tile location. There doesn't seem to be any position property for the Tile class (the Tile knows nothing about its location), so the Tilemap must have the answer. I was not able to find anything in the Unity documentation for how to get the Vector3 coordinates for a selected tile in the Tilemap.
I couldn't find a way to get the Grid's position from mouse click, so instead I used a Raycast to
Vector3
, and then converted that to coordinates via theWorldToCell
method of the Grid component as per Shirotha's suggestion. This allows me to move the selectedGameObject
to a new position.On an aside, I know how to get the Grid location, but now how to query it. I need to get the GridSelection static object from Grid, and then get its position.
If you have access to the
Tile
instance you can use its transform (or the raycast hit from the click) to get its world position and than get the tile coordinates via theWorldToCell
method of yourGrid
component (look at the documentation).EDIT:
Unity seems to not instantiate the tiles but instead uses only one tile object to manage all tiles of that type, i wasn't aware of that.
To get the correct position you have to calculate it yourself. Here is an example of how to get the tile position at the mouse cursor if the grid is positioned at the xy-plane with z = 0