I have a grid in my game that I store in a Dict Dictionary<Coord, Cell> cells = new Dictionary<Coord, Cell>();
where Coord
is:
public Coord(int x, int z)
{
this.x = x;
this.z = z;
}
And Cell
simply contains some int and string variables.
To get a specific cell I use:
public Cell GetCell(Coord coord)
{
if (IsCoordWithinBorder(coord))
return cells[coord];
return null;
}
Where IsCoordWithinBorder
looks like:
public bool IsCoordWithinBorder(Coord coord)
{
return coord.x >= 0 && coord.z >= 0 && coord.x < size && coord.z < size;
}
This seems to generate a ton of garbage, and I have no clue why.
One instance it creates a lot of garbage is when I try to find all surrounding cells:
public List<Cell> GetSurroundingCells(Coord coord, int distance)
{
List<Cell> matches = new List<Cell>();
for (int x = coord.x - distance; x <= coord.x + distance; x++)
{
for (int z = coord.z - distance; z <= coord.z + distance; z++)
{
Cell cell = GetCell(new Coord(x, z));
if (cell != null)
matches.Add(GetCell(new Coord(x, z)));
}
}
return matches;
}
From what I can gather from the Unity profiler, it all points to my GetCell()
-method. Am I doing something wrong here?
EDIT:
for (int x = 0; x < size; x++)
{
cells[x] = new Dictionary<int, Cell>();
for (int z = 0; z < size; z++)
{
cells[x][z] = new Cell();
}
}