Array inside a serializable class is not initialized properly

Hi. I want to create a simple high score table in the UI text. I use the highScoreEntries variable to keep the high scores.

But if I try to access highScoreEntries.table without calling the JsonUtility.ToJson(highScoreEntries) method before, it gives me a NullReferenceException for accessing highScoreEntries.table.

Thx.

public class HighScore : MonoBehaviour
{
    [SerializeField] private Text bestScoreText;

    private HighScoreEntries highScoreEntries = new HighScoreEntries();

    void Start()
    {
        print(JsonUtility.ToJson(highScoreEntries));          // This is the line

        UpdateHighScoreTable();
    }

    private void UpdateHighScoreTable()
    {
        bestScoreText.text = string.Empty;
        
        for (int index = 0; index < highScoreEntries.table.Length; index++)
        {
            bestScoreText.text += index + 1 + " " + highScoreEntries.table[index].playerName + " " + highScoreEntries.table[index].highScore + "

";
}
}

    #region Data Persistence

    [Serializable]
    class HighScoreEntries
    {
        [Serializable]
        public class SingleScoreEntry
        {
            public int highScore = 0;
            public string playerName = "-";
        }
        
        public SingleScoreEntry[] table = new SingleScoreEntry[5];
    }

 // public void SaveHighScoreEntries()

 // private void LoadHighScoreEntries()

    #endregion
}

If you add a Debug.Log(highScoreEntries.table) and the length is 0.

Probably this line
public SingleScoreEntry[] table = new SingleScoreEntry[5];

is being ignored or overwritten by the serialized object. So you have to override the constructor in order to create the array.

 [Serializable]
    class HighScoreEntries
    {
        [Serializable]
        public class SingleScoreEntry
        {
            public int highScore = 0;
            public string playerName = "-";
        }
         
        public SingleScoreEntry[] table;
        public HighScoreEntry()
        {
            table = new SingleScoreEntry[5];
        }
    }