问题描述
在枚举地图上的所有图块位置时,我发现自己经常使用以下模式:
for (int y = (int) map.Rect.y; y < map.Rect.yMax; y++)
{
for (int x = (int) map.Rect.x; x < map.Rect.xMax; x++)
{
// do something with X and Y coordinates
}
}
我一直在研究 IEnumerator 和 IEnumerable,但我不知道如何将它们实现到 Map。
我想达到的目标:
foreach (Vector3Int position in Map)
{
DoSomething(position.x,position.y);
}
然后 Map 可以使用这种更简单的语法在内部处理其余的逻辑。
解决方法
你可以yield
他们:
public IEnumerable<Point> AllMapPoints()
{
for (int y = (int) map.Rect.y; y < map.Rect.yMax; y++)
{
for (int x = (int) map.Rect.x; x < map.Rect.xMax; x++)
{
yield return new Point(x,y);
}
}
}
现在您可以将它们全部循环:
foreach (var point in AllMapPoints())
{
DoSomething(point.X,point.Y);
}
或者只是一些,例如:
foreach (var point in AllMapPoints().Take(100))
{
DoSomething(point.X,point.Y);
}