Reputation: 1232
I want to have all of the cells in a Tilemap into an array, I've tried:
Vector3Int[] Example = Examplemap.cellBounds
but that didn't work. Please help me
Upvotes: 0
Views: 1759
Reputation: 125245
Enumerate over Tilemap.cellBounds.allPositionsWithin
which should return BoundsInt
in each loop. Use the HasTile
to check if there is a tile that position in the Tilemap
. If there is a tile in that position, use Tilemap.CellToWorld
to covert the position to world then add it to a List
.
List<Vector3> GetCellsFromTilemap(Tilemap tilemap)
{
List<Vector3> worldPosCells = new List<Vector3>();
foreach (var boundInt in tilemap.cellBounds.allPositionsWithin)
{
//Get the local position of the cell
Vector3Int relativePos = new Vector3Int(boundInt.x, boundInt.y, boundInt.z);
//Add it to the List if the local pos exist in the Tile map
if (tilemap.HasTile(relativePos))
{
//Convert to world space
Vector3 worldPos = tilemap.CellToWorld(relativePos);
worldPosCells.Add(worldPos);
}
}
return worldPosCells;
}
To use:
Tilemap Examplemap = ...;
List<Vector3> cells = GetCellsFromTilemap(Examplemap);
If you prefer the cell positions to be returned in local space, replace tilemap.CellToWorld(relativePos)
with tilemap.CellToLocal(relativePos)
.
List<Vector3> GetCellsFromTilemap(Tilemap tilemap)
{
List<Vector3> worldPosCells = new List<Vector3>();
foreach (var boundInt in tilemap.cellBounds.allPositionsWithin)
{
//Get the local position of the cell
Vector3Int relativePos = new Vector3Int(boundInt.x, boundInt.y, boundInt.z);
//Add it to the List if the local pos exist in the Tile map
if (tilemap.HasTile(relativePos))
{
//Convert to world space
Vector3 localPos = tilemap.CellToLocal(relativePos);
worldPosCells.Add(localPos);
}
}
return worldPosCells;
}
Finally, if you just want the Vector2Ints
with no conversion then just add the data from the loop directly to the List
:
List<Vector3Int> GetCellsFromTilemap(Tilemap tilemap)
{
List<Vector3Int> cells = new List<Vector3Int>();
foreach (var boundInt in tilemap.cellBounds.allPositionsWithin)
{
//Get the local position of the cell
Vector3Int relativePos = new Vector3Int(boundInt.x, boundInt.y, boundInt.z);
//Add it to the List if the local pos exist in the Tile map
if (tilemap.HasTile(relativePos))
cells.Add(relativePos);
}
return cells;
}
Upvotes: 1