Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.

Help with assigning array data on scriptable object

Discussion in 'Scripting' started by gdg, Jul 24, 2015.

  1. gdg

    gdg

    Joined:
    Jul 8, 2013
    Posts:
    18
    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:

    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3. using System.Collections.Generic;
    4. using System.Linq;
    5. [System.Serializable]
    6. public class EachLevel
    7. {
    8.      public uint mLevelID;
    9.      public uint mSceneID;
    10. };
    11. [System.Serializable]
    12. public class LevelData : ScriptableObject
    13. {
    14.      public EachLevel lvl;
    15.      public void Init ( uint id1, uint id2 )
    16.      {
    17.          lvl.mLevelID = id1;
    18.          lvl.mSceneID = id2;
    19.      }
    20. }
    But this one does not:

    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3. using System.Collections.Generic;
    4. using System.Linq;
    5. [System.Serializable]
    6. public class EachLevel
    7. {
    8.      public uint mLevelID;
    9.      public uint mSceneID;
    10. };
    11. [System.Serializable]
    12. public class LevelData : ScriptableObject
    13. {
    14.      public EachLevel[] lvl;
    15.      public void Init ( uint id1, uint id2 )
    16.      {
    17.          lvl = new EachLevel[2];
    18.          lvl[0].mLevelID = id1;
    19.          lvl[0].mSceneID = id2;
    20.          lvl[1].mLevelID = id2;
    21.          lvl[1].mSceneID = id1;
    22.      }
    23. }
    Any idea why?
     
  2. DonLoquacious

    DonLoquacious

    Joined:
    Feb 24, 2013
    Posts:
    1,667
    You've created a new array but you haven't created any EachLevel objects.
    Code (csharp):
    1. lvl = new EachLevel[2];
    2. lvl[0] = new EachLevel();
    3. lvl[0].mLevelID = id1;
    4. lvl[0].mSceneID = id2;
    5. lvl[1] = new EachLevel();
    6. lvl[1].mLevelID = id2;
    7. lvl[1].mSceneID = id1;
     
    gdg likes this.
  3. gdg

    gdg

    Joined:
    Jul 8, 2013
    Posts:
    18
    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.