我想将Tilemap中的所有单元格都放入一个数组,我尝试过:
Vector3Int[] Example = Examplemap.cellBounds
但这没用。请帮助我
答案 0 :(得分:1)
枚举Tilemap.cellBounds.allPositionsWithin
,在每个循环中应返回BoundsInt
。使用HasTile
检查Tilemap
中是否有该位置的图块。如果该位置有一块图块,请使用Tilemap.CellToWorld
将位置隐蔽到世界中,然后将其添加到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;
}
要使用:
Tilemap Examplemap = ...;
List<Vector3> cells = GetCellsFromTilemap(Examplemap);
如果您希望将单元格位置返回本地空间,请用tilemap.CellToWorld(relativePos)
替换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;
}
最后,如果只希望Vector2Ints
不进行转换,则只需将循环中的数据直接添加到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;
}