Reputation: 7589
I have a big part of code like this that iterate trough an array
void GetSpawnablePosition() {
Vector2[] coordX = { Vector2.up, Vector2.down };
Vector2[] coordY = { Vector2.left, Vector2.right };
for (int i = 0; i < coordY.Length; i++)
{
Vector2[] newArray = new Vector2[enemyGrid.grid[0].Length - 2];
if (coordY[i] == Vector2.left)
{
for (int j = 0; j < enemyGrid.grid[0].Length - 2; j++)
{
newArray[j] = new Vector2(0, j+1);
}
}
if (coordY[i] == Vector2.right)
{
for (int j = 0; j < enemyGrid.grid[0].Length - 2; j++)
{
newArray[j] = new Vector2(enemyGrid.grid[0].Length - 1, j + 1);
}
}
spawnablePosition.Add(coordY[i], newArray);
}
for (int i = 0; i < coordY.Length; i++)
{
Vector2[] newArray = new Vector2[enemyGrid.grid.Length - 1];
if (coordX[i] == Vector2.down)
{
for (int j = 0; j <= enemyGrid.grid.Length - 2; j++)
{
newArray[j] = new Vector2(j+1,0);
}
}
if (coordX[i] == Vector2.up)
{
for (int j = 0; j <= enemyGrid.grid.Length - 2; j++)
{
newArray[j] = new Vector2(j + 1, enemyGrid.grid[0].Length - 1);
}
}
spawnablePosition.Add(coordX[i], newArray);
}
}
The snippet is supposed to take the index x and y of a grid
and
put it in a dictionary like this
Vector2.up => [[0][1],[0][2],[0][3],[0][4],[0][5]]
Vector2.left=> [[1][0],[2][0],[3][0],[4][0],[5][0]]
Vector2.right=> [[1][6],[2][6],[3][6],[4][6],[5][6]]
Vector2.down=> [[6][1],[6][2],[6][3],[6][4],[6][5]]
I tried to refactor it to make it smaller or more clear, but really, I honestly can't find a good solution that make that big thing smaller.
Can someone help me ?
Upvotes: 0
Views: 46
Reputation: 2554
Something like:
var yLength = enemyGrid.grid[0].Length;
var xLength = enemyGrid.grid.Length;
spawnablePosition.Add(Vector2.left, Enumerable.Range(1, yLength).Select(y => new Vector2(0, y)).ToArray());
spawnablePosition.Add(Vector2.right, Enumerable.Range(1, yLength).Select(y => new Vector2(xLength - 1, y)).ToArray());
spawnablePosition.Add(Vector2.up, Enumerable.Range(1, xLength).Select(x => new Vector2(x, 0)).ToArray());
spawnablePosition.Add(Vector2.down, Enumerable.Range(1, xLength).Select(x => new Vector2(x, yLength - 1)).ToArray());
Ensure that I don't mess with corresponding array lengths.
Upvotes: 1