Untitled

 avatar
unknown
csharp
a year ago
2.3 kB
24
Indexable
public class ConvertTilemapToGameObjects : MonoBehaviour
    {
        [SerializeField] private Tilemap _tilemap;
        [SerializeField] private GameObject _container;
        [SerializeField] private List<GameObject> _availableTiles;

        private Dictionary<string, GameObject> _availableTilesDictionary = new Dictionary<string, GameObject>();

        private void Start()
        {
            // Initialize the dictionary and convert the tilemap to game objects.
            InitializeTileDictionary();
            ConvertTilemap();

            // Deactivate the original tilemap.
            _tilemap.gameObject.SetActive(false);
        }

        private void InitializeTileDictionary()
        {
            _availableTilesDictionary = new Dictionary<string, GameObject>();
            foreach (var tile in _availableTiles) _availableTilesDictionary.Add(tile.name, tile);
        }

        private void ConvertTilemap()
        {
            // Get the bounds of the tilemap.
            BoundsInt _bounds = _tilemap.cellBounds;

            // Iterate through the tilemap's tiles.
            for (int z = _bounds.max.z; z >= _bounds.min.z; z--)
            {
                for (int y = _bounds.min.y; y < _bounds.max.y; y++)
                {
                    for (int x = _bounds.min.x; x < _bounds.max.x; x++)
                    {
                        // Get the position of the current tile.
                        var tilePosition = new Vector3Int(x, y, z);

                        // Check if the tilemap has a tile at the current position
                        if (_tilemap.HasTile(tilePosition))
                        {
                            // Check if the tile is not in the dictionary.
                            if (!_availableTilesDictionary.ContainsKey(_tilemap.GetTile(tilePosition).name)) Debug.LogWarning("Tile " + _tilemap.GetTile(tilePosition).name + " not in dictionary");

                            // Instantiate the corresponding game object at the tile position.
                            Instantiate(_availableTilesDictionary[_tilemap.GetTile(tilePosition).name], _tilemap.CellToWorld(tilePosition) + new Vector3(0, 0.08f, 0), Quaternion.identity, _container.transform);
                        }
                    }
                }
            }
        }
    }
Editor is loading...
Leave a Comment