Flatten 2D array in Unity C#

Published

I like using Unity’s Scriptable Objects. I think they are a neat feature and incredibly useful. There do have one problem: they use the Unity serializer which means it does not support 2D arrays which is why I had to write this utility to convert them to 1D array.

Also, while 2D arrays are easier to make sense of, 1D arrays are usually more performant and .Net has some optimizations for them, see https://mdfarragher.medium.com/high-performance-arrays-in-c-2d55c04d37b5

Anyways, the trick to convert from 2D to 1D is to consider the 1D coordinates of a 2D point as: x + y * width. That’s all that’s needed!

The code is available below, or on my github along with other utilities.

public static class ArrayFlattener
{

    public static T[] Flatten<T>(T[,] input)
    {
        int width = input.GetLength(0);
        int height = input.GetLength(1);
        T[] flattened = new T[width * height];

        for (int j = 0; j < height; j++)
        {
            for (int i = 0; i < width; i++)
            {
                flattened[j * width + i] = input[i, j];

            }
        }

        return flattened;
    }


    public static T[,] Unflatten<T>(T[] input, int width, int height)
    {
        T[,] unflattened = new T[width, height];

        for (int j = 0; j < height; j++)
        {
            for (int i = 0; i < width; i++)
            {
                unflattened[i, j] = input[j * width + i];

            }
        }

        return unflattened;

    }

}