Source file unity-csharp/nature-of-code/cellular-automata-game-of-life/GameOfLifeGrid.cs from the GDnD code examples. Download raw file

// GDnD wiki example
// Demonstrates: Game of Life grid stepping in Unity 2D
// Related pages: [[cellular-automata]], [[overview-unity-nature-of-code-examples]]
 
using UnityEngine;
 
public class GameOfLifeGrid : MonoBehaviour
{
    [SerializeField] private int width = 64;
    [SerializeField] private int height = 64;
    [SerializeField, Range(0f, 1f)] private float aliveChance = 0.45f;
 
    private bool[,] current;
    private bool[,] next;
 
    public int Width => width;
    public int Height => height;
    public bool[,] Current => current;
 
    private void Awake()
    {
        current = new bool[width, height];
        next = new bool[width, height];
        Randomise();
    }
 
    public void Randomise()
    {
        for (int x = 0; x < width; x++)
        for (int y = 0; y < height; y++)
            current[x, y] = Random.value < aliveChance;
    }
 
    public void Step()
    {
        for (int x = 0; x < width; x++)
        for (int y = 0; y < height; y++)
        {
            int neighbours = CountNeighbours(x, y);
            bool alive = current[x, y];
            next[x, y] = alive
                ? neighbours == 2 || neighbours == 3
                : neighbours == 3;
        }
 
        (current, next) = (next, current);
    }
 
    private int CountNeighbours(int x, int y)
    {
        int sum = 0;
 
        for (int dx = -1; dx <= 1; dx++)
        for (int dy = -1; dy <= 1; dy++)
        {
            if (dx == 0 && dy == 0)
                continue;
 
            int nx = (x + dx + width) % width;
            int ny = (y + dy + height) % height;
 
            if (current[nx, ny])
                sum++;
        }
 
        return sum;
    }
}