NullReferenceException on an array

I got this error message, I don’t get it was is wrong:

NullReferenceException: Object reference not set to an instance of an object
HighScoreScript.LoadHighScore () (at Assets/!MyGame/Scripts/HighScoreScript.cs:51)
GameManagerScript.LoadGame () (at Assets/!MyGame/Scripts/GameManagerScript.cs:253)
GameManagerScript.Awake () (at Assets/!MyGame/Scripts/GameManagerScript.cs:68)

public class HighScoreSingle
{
    public int highScore;
    public int difficulty;
    public int playerHealth;
    public int enemyHealth;
    public int bossHealth;
    public string stageStart;
    public string stageEnd;
    public string timeDate;

    public HighScoreSingle(int highScore = 0, int difficulty = 0, int playerHealth = 0, int enemyHealth = 0, int bossHealth = 0, string stageStart = "", string stageEnd = "", string timeDate = "")
    {
        this.highScore = highScore;
        this.difficulty = difficulty;
        this.playerHealth = playerHealth;
        this.enemyHealth = enemyHealth;
        this.bossHealth = bossHealth;
        this.stageStart = stageStart;
        this.stageEnd = stageEnd;
        this.timeDate = timeDate;
    }
    public const int numberMax = 10;
    public HighScoreSingle[] highScoreSingle = new HighScoreSingle[numberMax];

if I use this I got no error:

Debug.Log("highScoreSingle " + highScoreSingle[0]);

But if I use this I get the NullReferenceException:

Debug.Log("highScoreSingle " + highScoreSingle[0].highScore);

It seems I’m blind to the error, what is wrong?

You’re making an array with a length of 10, but you don’t actually initialise any elements into it. So it’s just an array of null-pointers to begin with. You need to create instances of HighScoreSingle and add them to the array.

So you probably need to add a parameterless constructor so you can add ‘empty’ high score objects to the array.

3 Likes

Sorry I feel very stupied but I don’t get it, could you please write an example code?

And my constructor have default values, should this not be enough?

Just so you’re aware, this is basic C# stuff. Arrays that aren’t initialized on creation will have their elements be the default value. For reference types (class types), this is null, so every element is null by default. new T[n] does not automatically create new instances for each element. You need to add a for loop and assign a new object to each element individually.
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/arrays
Spiney said the same thing. Hopefully the different phrasing and doc are enlightening.

2 Likes

And I did miss the default parameters on the constructor, so it will suffice as a parameterless constructor for a default/empty high score entry.

2 Likes

Ok, got it, thank you and thanks @spiney199 you too!