Help with assigning array data on scriptable object

For my current project I have to read data from CSV files and I’d like to store the data in scriptable objects.
When I try to assign ordinary fields I don’t get any problems but if I try to assign an array I get a NullReferenceException.

The following code works:

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
[System.Serializable]
public class EachLevel
{
     public uint mLevelID;
     public uint mSceneID;
};
[System.Serializable]
public class LevelData : ScriptableObject
{
     public EachLevel lvl;
     public void Init ( uint id1, uint id2 )
     {
         lvl.mLevelID = id1;
         lvl.mSceneID = id2;
     }
}

But this one does not:

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
[System.Serializable]
public class EachLevel
{
     public uint mLevelID;
     public uint mSceneID;
};
[System.Serializable]
public class LevelData : ScriptableObject
{
     public EachLevel[] lvl;
     public void Init ( uint id1, uint id2 )
     {
         lvl = new EachLevel[2];
         lvl[0].mLevelID = id1;
         lvl[0].mSceneID = id2;
         lvl[1].mLevelID = id2;
         lvl[1].mSceneID = id1;
     }
}

Any idea why?

You’ve created a new array but you haven’t created any EachLevel objects.

lvl = new EachLevel[2];
lvl[0] = new EachLevel();
lvl[0].mLevelID = id1;
lvl[0].mSceneID = id2;
lvl[1] = new EachLevel();
lvl[1].mLevelID = id2;
lvl[1].mSceneID = id1;
1 Like

Oh, I din’t know I had to do that despite using arrays and classes for so long. I tried it and it works perfectly. Thank you! I had also posted this question yesterday in Unity answers but it seems that the forums are more active than unity answers.