Search Unity

How can I change sprite of one tile.

Discussion in '2D' started by tajnz11234, Sep 19, 2018.

  1. tajnz11234

    tajnz11234

    Joined:
    Sep 19, 2018
    Posts:
    2
    Hello everyone. I am trying to change sprite of specific tile in tilemap. I came up with something like this.

    Code (CSharp):
    1.     public Tilemap tilemap;
    2.     public Sprite[] sprites;
    3.  
    4.     void Start () {
    5.      
    6.     }
    7.  
    8.     public void ChangeTileTexture(Vector3Int coord)
    9.     {
    10.         coord.y -= 1;//it's one tile off from y
    11.         Tile tile = (Tile)tilemap.GetTile(coord);
    12.         Debug.Log("TExture '" + tile.sprite.ToString() + "'");
    13.         tile.sprite = sprites[0];
    14.         Debug.Log("TExture 2'" + tile.sprite.ToString() + "'");
    15.     }
    Log says that texture was changed but it doesnt change anything in the game or scene view. Sometimes when i hit play it changes sprite of every tile, it somehow replaces sprite in Tile Palette.

    How can I make it work?
     
    Last edited: Sep 19, 2018
  2. tajnz11234

    tajnz11234

    Joined:
    Sep 19, 2018
    Posts:
    2
    OK I figured it out.

    Code (CSharp):
    1.     public Tilemap tilemap;
    2.     public Sprite[] sprites_dig;
    3.     // Use this for initialization
    4.     void Start () {
    5.      
    6.     }
    7.  
    8.     public void ChangeTileTexture(Vector3Int coord)
    9.     {
    10.         Tile tile = ScriptableObject.CreateInstance<Tile>();
    11.         tile.sprite = sprites_dig[0];
    12.         coord.y -= 1;//it's one tile off from y
    13.         tilemap.SetTile(coord, tile);
    14.         Debug.Log("Texture '" + tile.sprite.ToString() + "'");
    15.     }
     
  3. Wecica

    Wecica

    Joined:
    Jul 20, 2016
    Posts:
    27
    Have you implemented changing a single tile's sprite during runtime?
     
  4. ChuanXin

    ChuanXin

    Unity Technologies

    Joined:
    Apr 7, 2015
    Posts:
    1,068
    The above solution will work in runtime. If you have an existing Tile with the Sprite you want to change to, you can directly call
    tilemap.SetTile(coord, tile)
    without having to create a new Tile.