How to Change Tile Sprite in Runtime in Unity?

Hello,

I want to make a mini city builder game and i use tiled for generating a map. I can click to object tiles but there is no component for changing the sprite of a tile. How can i change a tiles’ sprite in runtime in unity?

Thank you for your answers.

What do you mean by “a tile’s sprite”? Tiles and sprites are usually distinct concepts.

Do you mean changing which tile is displayed at a given location? After importing your map, you’ll have some sort of representation of the tiles in your game (the representation depends on how you import the maps), you should be able to change it with scripts just as you would change anything else in your game. Depending on your in-engine representation of the map, this may be as simple as changing the tile ID in the appropriate layer, or it may require changing the texture coordinates of each changed tile (same thing, just with a little more math).

If you’re making a game that requires a lot of changes to the map at runtime, it may be good to build your own Tiled importer (with only the features you actually need for your game), so that you can have full control of the in-engine map and can write code to make modifying it simple.

1 Like

You actually can change the sprite of a tile, because tiles have reference to a sprite. First you need to get your tile information
Vector3Int tilePos;
TileBase tileBase = tilemap.GetTile(tilePos);

now you change the sprite but to do that first you need to cast your tileBase to a Tile

var tile = (Tile)tileBase;

otherwise you won’t be able to change it.

tile.sprite = newSprite;
tilemap.SetTile(tilePos, tile);

Finally you need to refresh your tilemap

tilemap.RefreshTile(tilePos);