Easy 2D Array Declaration

Hi All,

I have the below table on an Excel sheet and want to create 2D array. What I know so far is the below way of declaration. Is there any better practice in C#? Because the size might be larger in the future. Thanks.

    public int[,] myarray = new int[9,9];

    private void Awake()
    {
        myarray[0, 0] = 1;
        myarray[0, 1] = 9;
        myarray[0, 2] = 2;
        myarray[1, 0] = 8;
        ...
    }

1 9 2 1 4 2 4 5 7
8 9 8 6 1 5 8 5 3
5 8 2 1 4 2 4 5 8
8 6 2 8 1 9 4 6 6
7 5 8 1 4 1 5 5 3
7 2 2 6 7 3 1 2 5
7 2 1 8 2 9 3 6 4
5 2 1 2 2 5 6 2 8
6 1 8 4 8 7 4 9 3

If you could find a way to read from the Excel sheet (or convert the Excel sheet into a .txt file), you could loop over it and have it all done by code instead of manually inserting values into the array. Something like :

using UnityEngine;
using System.IO;
using System.Linq;
using System.Collections.Generic;

public class MyScript : MonoBehaviour
{
    public int[,] myarray;

    List<string> fileLines = new List<string>();

    private void Awake()
    {
        ReadFile();

        for (int y = 0; y < fileLines.Count; y++)
        {
            for (int x = 0; x < fileLines[y].Length; x++)
            {
                myarray[y, x] = int.Parse(fileLines[y].Substring(x));
            }
        }
    }

    private void ReadFile()
    {
        using (StreamReader sr = new StreamReader("whatever.txt"))
        {
            fileLines = sr.ReadToEnd().Split("\n"[0]).ToList();
        }
    }
}

Obviously you’ll need to change “whatever.txt” to the path of your txt file.

Edit: fixed error.

1 Like

Seems very practical. Thanks a lot :slight_smile:

public int[,] myarray = new[,]
{
    { 1, 9, 2, 1, 4, 2, 4, 5, 7, },
    { 8, 9, 8, 6, 1, 5, 8, 5, 3, },
    { 5, 8, 2, 1, 4, 2, 4, 5, 8, },
    ...
};
1 Like