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.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Null Reference Exception? I think I'm using arrays wrong...

Discussion in 'Scripting' started by candlemaster, Feb 1, 2015.

  1. candlemaster

    candlemaster

    Joined:
    Mar 12, 2014
    Posts:
    16
    So I'm trying to track down some weird errors, and I believe that I've narrowed it down to this block of code:

    private Skill[] _skills;
    private int[] _expTable;

    public void Awake()
    {
    // Allocate the array of skills and initialize them. //
    _skills = new Skill[(int)SkillName.MAX_SKILLS];
    for (int i = 0; i < (int)SkillName.MAX_SKILLS; ++i)
    {
    _skills.level = startingLevel;
    _skills.experience = 0;
    }

    // Allocate the experience table and initialize it. //
    _expTable = new int[maxLevel];
    for (int i = 0; i < maxLevel; ++i)
    {
    _expTable = (int)(expCurveConst + (i * expCurveScalar) + (i * i * expCurveSquare) + (i * i * i * expCurveCube));
    }
    }

    It appears that whenever I try to access the "_skills" array(including inside Awake), I get a null reference exception. What am I doing wrong? Is my error someplace completely different?

    I'm a C++ programmer mainly, and don't do much with C#, so I might just be making a newbie mistake...
     
  2. fire7side

    fire7side

    Joined:
    Oct 15, 2012
    Posts:
    1,819
    I think what you mean is:
    Code (csharp):
    1.  
    2. for (int i = 0; i < (int)SkillName.MAX_SKILLS; ++i)
    3. {
    4. _skills[i] = new Skill();
    5. _skills[i].level = startingLevel;
    6. _skills[i].experience = 0;
    7. }
    8.  
     
  3. candlemaster

    candlemaster

    Joined:
    Mar 12, 2014
    Posts:
    16
    That fixed it, thank you so much!

    In C++ when I allocate an array of objects, it allocates and initializes the objects themselves... bah.