I want to change Tile's sprite during runtime, but it doesn't render.
class SwitchableTile : Tile
{
// usable sprites
public Sprite[] sprites;
// index to the sprite
private int spriteIndex = 0;
// I don't know when it's called
// but set sprite to current spriteIndex
public override void GetTileData(Vector3Int position, ITilemap tilemap, ref TileData tileData)
{
// ..
if (sprites != null && sprites.Length > 0)
{
tileData.sprite = sprites[spriteIndex];
}
}
// called per Tilemap.RefreshTile
public override void RefreshTile(Vector3Int position, ITilemap tilemap)
{
tilemap.RefreshTile(position);
}
}
Also tried to refresh the tile according to the position:
// in MonoBehaviour
BoundsInt bounds = tilemap.cellBounds;
bool updated = false;
foreach (Vector3Int pos in bounds.allPositionsWithin)
{
TileBase tile = tilemap.GetTile(pos);
if (tile && tile is SwitchableTile)
{
if (!updated)
{
// just loop index
Sprite sprite = ((SwitchableTile)tile).GetNextSprite();
// set sprite
((SwitchableTile)tile).sprite = sprite;
updated = true;
}
// refresh
tilemap.RefreshTile(pos);
}
}
Since Tilemap.RefreshTile
calls TileBase.RefreshTile
per refresh, the problem's solved after I implemented TileBase.RefreshTile
.
I'm not using 2d-extra's animation tile because I want to change sprites only under certain condition. Also not using Tilemap.SwapTile because in this case I'm solving it using customized Tile, instead of creating a new Tile.
Update: Well...It proves that I need to implement RefreshTile
for a Tile. Now the sprite refreshes. But I'm still not sure about GetTileData
, do I need to implement it? When it is called?
GetTileData
, I would be also appreciate if anyone else also provides an answer. \$\endgroup\$