0

I use this code to be written in an array

But an error

void Start () 
{
    List<int>[,] li = new List<int>[8,5];
    li[0,0].Add(15);  //error in here
    Debug.Log(li[0,0][0]);
}

This is the error message

NullReferenceException: Object reference not set to an instance of an object Word.Start () (at Assets/Script/Word.cs:19)

I wanted to use List and arrays allocated objects, but I found

li[0,0].Add(15);

A mistake, I made it the wrong way?

croxy
  • 4,082
  • 9
  • 28
  • 46

1 Answers1

2

You should create a List<int> instance:

// create a list, add 15 to it and put the list into [0, 0] cell
li[0, 0] = new List<int>(){15};  

Since List<int>[,] li = new List<int>[8,5]; creates an array only and fills it with nulls. You can create all the lists in a loop and then safely use Add:

   List<int>[,] li = new List<int>[8,5];

   for (int r = 0; r < li.GetLength(0); ++r)
     for (int c = 0; c < li.GetLength(1); ++c)
       li[r, c] = new List<int>();

   li[0,0].Add(15);
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215