Search Unity

Check for current tile in tilemap before placing them?

Discussion in '2D' started by florianhanke, Mar 5, 2021.

  1. florianhanke

    florianhanke

    Joined:
    Jun 8, 2018
    Posts:
    426
    I'm writing my own custom tile. Is there a possibility to figure out if the tile in
    `GetTileData(Vector3Int position, ITilemap tilemap, ref TileData tileData)` is the one currently being hovered over (not yet being placed)?
     
  2. Lo-renzo

    Lo-renzo

    Joined:
    Apr 8, 2018
    Posts:
    1,513
    You could try converting the screenspace position of the mouse to worldspace then finally to cellspace of the grid.
    Code (CSharp):
    1.     var mouseWorldPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
    2.     mouseWorldPos.z = 0f; // zero z
    3.     var cellHovered = tilemap.WorldToCell(mouseWorldPos);
    4.  
    The problem is that it's ITilemap, which isn't a real tilemap. I can't quite recall but I think you can call GetComponent on it and that'll get the real Tilemap or let you get to it.

    But that might not be the best place to put this logic because it'll fire every time that tile refreshes. Are you building a custom brush? Inside one of the brush hooks is a more sensible place to put that check. But there you should already have the cell in question so it shouldn't be necessary.
     
    florianhanke likes this.
  3. florianhanke

    florianhanke

    Joined:
    Jun 8, 2018
    Posts:
    426
    Thank you – I am working on a conveyor belt tile, which needs some sort of information stored on each tile as to where its input and output is. However, I noticed that during edit time, a GameObject (with that information) is not added on the Tilemap, only during run time. So I am not sure that using a Tilemap is the way to go (although it is working well, only that the direction it moves in is not stable).
     
  4. Lo-renzo

    Lo-renzo

    Joined:
    Apr 8, 2018
    Posts:
    1,513
    Most people eventually find they need to build a data structure (array / dictionary) parallel to the tilemap to store per-instance data, e.g. hitpoints... or conveyor state. This complicates working in the editor. If limited in #, gameobjects should be fine.
     
    florianhanke likes this.
  5. florianhanke

    florianhanke

    Joined:
    Jun 8, 2018
    Posts:
    426
    Since GOs are not created during edit time, I'll probably have to move to a parallel data structure – thanks for confirming!