Obtain Sprite Data from Tile in a Grid Using Tile Coordinates
Hello All,
I am trying to get the sprite data of a particular tile (a tile clicked on) in a grid. My goal is to modify this sprite value with a different sprite. However, I cannot figure out how to access any data from the tile. I started with the sprite data, but I have had no luck. The following code is the closest I've been to discovering how to solve this issue:
 //The Grid GameObject that contains the tilemaps
 public Grid grid;
 public void Update()
 {
     //Detect when mouse is clicked
     if (Input.GetMouseButtonDown(0))
     {
         //Get position of the mouseclick
         Vector3 mouseWorldPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
         //Convert position of the mouseclick to the position of the tile located at the mouseclick
         Vector3Int coordinate = grid.WorldToCell(mouseWorldPos);
         //Display tile position in log
         Debug.Log(coordinate);
         //Display the sprite value of the tile in log *This part is failing*
         Debug.Log(Tilemap.GetSprite(coordinate));
     }
 }
 
               ....
I'm getting the error: An object reference is required for the non-static field, method, or property 'Tilemap.GetSprite(Vector3Int)'.
....
Please help me understand what I am doing wrong, and if there is a better way to solving this. Thank you!
Answer by NezzyGuda · Dec 29, 2018 at 11:24 PM
I FIGURED IT OUT! Turns out, I was using the GetSprite function wrong lol. Tilemap isn't a call, it is meant to be an object reference to a defined Tilemap object (I think I said that right). Basically, I just had to create a public Tilemap object and associate it with one of my tilemaps, and boom! I can get the tile data from any sprite across diferent tilemaps! EXACTLY what I needed. I hope this helps anyone out there struggling like I was...
 public Grid grid; //Set a Grid or Tilemap object to this in the Editor
 public Tilemap myTileMap; //Set a Tilemap object to this in the Editor
 public void Update()
 {
     
     //Detect when mouse is clicked
     if (Input.GetMouseButtonDown(0))
     {
         //Get position of the mouseclick
         Vector3 mouseWorldPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
         //Convert position of the mouseclick to the position of the tile located at the mouseclick
         Vector3Int coordinate = grid.WorldToCell(mouseWorldPos);
         //Display tile position in log
         Debug.Log(coordinate);
         //Display the sprite value of the tile in log *SUCCESS*
         Debug.Log(myTileMap.GetSprite(coordinate));
     }
 }
 
              Your answer