Home > database >  How can I Initialize an array in class?
How can I Initialize an array in class?

Time:06-19

public class DataClass
{
    public int[] collectionData;
}

[SerializeField] private DataClass[] DataClassArray;

I have created above field in which class consists of an array, and the object of that class is also an array.

public void GenerateCategariesData()
{
    Debug.Log("==========>******"   bookCatogaryObject.Data.Rows.Count);

    collectionCounts = new int[bookCatogaryObject.Data.Rows.Count];

    DataClassArray = new DataClass[bookCatogaryObject.Data.Rows.Count];

    for (int i = 0; i <= bookCatogaryObject.Data.Rows.Count; i  )
    {
        Debug.Log("==========>######"   bookCatogaryObject.Data.Rows[i].String.Count);
        ***collectionCounts[i] = bookCatogaryObject.Data.Rows[i].String.Count;***

        ***DataClassArray[i].collectionData = new int[bookCatogaryObject.Data.Rows[i].String.Count];***

        for (int m = 0; m < bookCatogaryObject.Data.Rows[i].String.Count; m  )
        {
            Debug.Log(bookCatogaryObject.Data.Rows[i].String[m].CollectionTitle);
        }
    }
}

Here is the method where I'm trying to initialize the arrays, but when I run the code I get an error "NullReferenceException: Object reference not set to an instance of an object" at Line : " DataClassArray[i].collectionData = new int[bookCatogaryObject.Data.Rows[i].String.Count];". Im not able to figure out where exactly the issue is.

CodePudding user response:

Add

DataClassArray[i] = new DataClass();

right before

DataClassArray[i].collectionData = new int[bookCatogaryObject.Data.Rows[i].String.Count];

When you create an array, each element is null, so you need to create an element before trying to access its members.

  • Related