I'm working on a Game Of Life clone as my first project. I'm still relatively new to programming, so my code is probably not really optimised.
The biggest bottleneck is in my Start()
method, but that contains a lot of Unity3D specific methods which most people here probably don't know about. That's why I'm leaving that out.
My second bottleneck is somewhere in my Update()
method. In here, I'm looping through my array which is currently 100 by 100 large, 10.000 in total.
I've been checking with the built-in profiler of Unity3D, and this reports that the biggest bottleneck is the garbage collection.
I also tried to put half of the loop in another thread, but that didn't work out properly, because it needs to look up cells in the other half.
If you see any other ways to improve my code, and not just the performance, feel free to let me know. But please, keep it simple, as I'm still relatively new to programming.
The relevant code:
void Update()
{
timeElapsed += Time.deltaTime; // this will add deltaTime to timeElapsed,
if (timeElapsed >= timeBetween) // until timeElapsed exceeds timeBetween,
{ // which allows a new generation to be calculated
timeElapsed -= timeBetween;
if (gameState == GameState.Game_Playing)
{
grid = CheckAdjacent(grid); // draw new generation
UpdateInformation(); // update information variables
}
}
}
public static void DrawGeneration(bool[,] grid)
{
for (int x = 0; x < gridX; x++)
{
for (int y = 0; y < gridY; y++)
{
cubeGrid[x,y].renderer.enabled = grid[x,y]; // enables the renderer for active cells.
}
}
}
private void UpdateInformation()
{
generation++; //counts the generations
}
public static int GetAliveCells ()
{
int i = 0;
for (int x = 0; x < gridX; x++)
{
for (int y = 0; y < gridY; y++)
{
if (grid[x, y]) // counts the number of alive cells
i++;
}
}
return i;
}
bool IsCellAlive(int adjacentCount, bool isAlive)
{
if (isAlive)
return liveRule.Contains(adjacentCount);
else
return becomeAliveRule.Contains(adjacentCount);
}
private bool[,] CheckAdjacent(bool[,] grid)
{
int adjacentSquares = 0;
bool[,] newGrid = new bool[gridX, gridY];
for (int x = 0; x < gridX; x++)
{
for (int y = 0; y < gridY; y++)
{
adjacentSquares = 0;
if (grid[calcX(x - 1), calcY(y - 1)])
adjacentSquares++;
if (grid[calcX(x), calcY(y - 1)])
adjacentSquares++;
if (grid[calcX(x + 1), calcY(y -1)])
adjacentSquares++;
if (grid[calcX(x - 1), calcY(y)])
adjacentSquares++;
if (grid[calcX(x + 1), calcY(y)])
adjacentSquares++;
if (grid[calcX(x - 1), calcY(y + 1)])
adjacentSquares++;
if (grid[calcX(x), calcY(y + 1)])
adjacentSquares++;
if (grid[calcX(x + 1), calcY(y + 1)])
adjacentSquares++;
newGrid[x,y] = IsCellAlive(adjacentSquares, grid[x,y]);
}
}
return newGrid;
}
private int calcX(int x)
{
x += gridX;
return (x % gridX);
}
private int calcY(int y)
{
y += gridY;
return (y % gridY);
}