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

// GDnD wiki example
// Demonstrates: Rendering a Game of Life grid to a Texture2D in Unity
// Related pages: [[cellular-automata]], [[overview-unity-nature-of-code-examples]]
 
using UnityEngine;
 
[RequireComponent(typeof(GameOfLifeGrid))]
[RequireComponent(typeof(SpriteRenderer))]
public class GameOfLifeTextureRenderer : MonoBehaviour
{
    [SerializeField] private float stepInterval = 0.1f;
 
    private GameOfLifeGrid grid;
    private Texture2D texture;
    private Color32[] pixels;
    private float timer;
 
    private void Awake()
    {
        grid = GetComponent<GameOfLifeGrid>();
        texture = new Texture2D(grid.Width, grid.Height, TextureFormat.RGBA32, false);
        texture.filterMode = FilterMode.Point;
        pixels = new Color32[grid.Width * grid.Height];
 
        Sprite sprite = Sprite.Create(texture, new Rect(0, 0, grid.Width, grid.Height), new Vector2(0.5f, 0.5f), 1f);
        GetComponent<SpriteRenderer>().sprite = sprite;
        Draw();
    }
 
    private void Update()
    {
        timer += Time.deltaTime;
 
        if (timer < stepInterval)
            return;
 
        timer = 0f;
        grid.Step();
        Draw();
    }
 
    private void Draw()
    {
        bool[,] cells = grid.Current;
 
        for (int x = 0; x < grid.Width; x++)
        for (int y = 0; y < grid.Height; y++)
            pixels[y * grid.Width + x] = cells[x, y] ? Color.white : Color.black;
 
        texture.SetPixels32(pixels);
        texture.Apply();
    }
}