I'm trying to take advantage of iterators in C# to clean up some spatial queries on objects in a game I'm making.
Here's what I'm doing currently:
public struct ObjectInfo
{
public int x, y;
public int Type;
public int hp;
}
public static IEnumerable<ObjectInfo> NearbyObjects(int x, int y, int distance)
{
// Not actually what I'm doing, but for simplicity...
for (int i = 0; i < 10; ++ i)
{
yield return new ObjectInfo();
}
}
public static void Explode()
{
foreach (ObjectInfo o in NearbyObjects(0, 0, 1))
{
o.hp = 0;
}
}
This works great except I think there is some boxing/unboxing going on. The CLRProfiler seems to verify this as I'm seeing allocations happening in my Explode method. I'd very much like to avoid any allocations after startup so I'm not triggering the garbage collector in the middle of a level or something. Is there some way I can keep this syntax while avoiding any allocation? Maybe by implementing my own iterators or something?