0

I have a class like this:

[System.Serializable]
public class arrayData
{
    public List<arrayData2> Levels;
}
public List<arrayData> Zones;

[System.Serializable]
public class arrayData2 { }

And I should add an item to the Levels collection:

void Start()
{
    Zones.Add(new arrayData());
    Zones[0].Levels.Add(new arrayData2());
}

The method keeps giving this error at runtime:

NullReferenceException: Object reference not set to an instance of an object

Does anybody know what am I missing?

Christoph Fink
  • 21,159
  • 9
  • 62
  • 101
sonny
  • 57
  • 5
  • 5
    [What is a NullReferenceException and how do I fix it?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Soner Gönül Jul 23 '14 at 06:11

4 Answers4

5

In arrayData you need an actual instance of Levels, which you can create in the constructor:

[System.Serializable]
public class arrayData
{
    public List<arrayData2> Levels;

    public arrayData() 
    {
        Levels = new List<arrayData2>();
    }
}

And you must create a new instance of Zones prior to using it:

var Zones = new List<arrayData>();
Zones.Add(new arrayData());
Zones[0].Levels.Add(new arrayData2());
Yuval Itzchakov
  • 136,303
  • 28
  • 230
  • 296
Dennis Traub
  • 46,924
  • 7
  • 81
  • 102
2

In your examples, you are missing to initialize the Zones and Levels collections.

You can either do it on the class that contains them or on the Start method.

For example, on the Start method:

void Start()
{
    var Zones = new List<arrayData>();
    Zones.Levels = new List<arrayData2>();

    Zones.Add(new arrayData());
    Zones[0].Levels.Add(new arrayData2());
}

Or on the class containing them:

[System.Serializable]
public class arrayData
{
    public List<arrayData2> Levels = new List<arrayData2>();
}
public List<arrayData> Zones = new List<arrayData>();

[System.Serializable]
public class arrayData2 { }
Nahuel Ianni
  • 3,071
  • 4
  • 21
  • 28
  • Thanks a lot, this made me understand the structure – sonny Jul 23 '14 at 07:23
  • That's what we are here for :) You can now follow the idea and implement it as you will (for example in the constructor of the class containing the list). – Nahuel Ianni Jul 23 '14 at 07:24
0

I believe that Zones is not initialized.

Codor
  • 16,805
  • 9
  • 30
  • 51
0

You need to initialize the Levels collection

public List<arrayData2> Levels;

You can do it in the ArrayData constructor or in Start() method

Atur
  • 1,392
  • 6
  • 26
  • 37