Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

Retrieving Cell Center from Tilemap

Discussion in 'Scripting' started by Zitant, May 29, 2019.

  1. Zitant

    Zitant

    Joined:
    May 26, 2019
    Posts:
    7
    Hello!

    I had this working yesterday but now it seems to be having an issue which I don't understand.

    Brief description before I post the code. I'm grabbing the world position of the mouse with WorldToScreenPoint and then using that to find the WorldToCell. When I call the GetCellCenter (Both Local and World) it gives me an error about not being able to convert Vector3 to Vector3Int even though the WorldToCell is a Vector3Int.

    Code (CSharp):
    1. private Tilemap tilemap;
    2.  
    3. void awake()
    4. {
    5. tilemap = GameObject.Find("Tilemap").GetComponent<Tilemap>();
    6. }
    7.  
    8. Void update()
    9. {
    10. Vector3 mousePos = Camera.main.WorldToScreenPoint(Input.mousePosition);
    11.  
    12. Vector3Int tilePos = tilemap.WorldToCell(mousePos);
    13.  
    14. Vector3Int tileCenter = tilemap.GetCellCenterLocal(tilePos);
    15.  
    16. }
    Yesterday, I had this bit of code working but I deleted it... for reasons...
    also side note, I can't seem to pull the tile information either. I try TileBase tile = tilemap.GetTile(tilePos) but in the console it only reports it as an object and throws an exception when I try to get the name or anything else.
     
  2. StarManta

    StarManta

    Joined:
    Oct 23, 2006
    Posts:
    8,748
    GetCellCenter returns a Vector3, and you're trying to put that into a Vector3Int (tileCenter). tileCenter should be a Vector3.
     
    Zitant likes this.
  3. Zitant

    Zitant

    Joined:
    May 26, 2019
    Posts:
    7
    Thanks for your Help!