Question by
montanaro94 · Mar 12, 2017 at 10:30 PM ·
c#listnullreferenceexceptionlistsdictionary
Getting "object reference not set" error when creating a list dictionary.
Hello,
I've recently seen a couple of suggestions here to make a list dictionary. I've been trying to do it, but I keep getting the error NullReferenceException: Object reference not set to an instance of an object. This happens on the line: "countryValuesDictionary.Add("Brazil", Brazil);" of the following script:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class createDictionary : MonoBehaviour {
public static Dictionary<string, List<float>> countryValuesDictionary;
public static Dictionary<string, List<float>> countryCompaniesDictionary;
void Awake()
{
if (countryValuesDictionary == null)
{
DontDestroyOnLoad(gameObject);
}
}
void Start()
{
createCountryDictionary();
}
public void createCountryDictionary () {
// First we create the dictionary for the characteristics of every country
// Value 1: national buying power in millions of US$
// Value 2: total national population
// Value 3:
// Value 4:
// Value 5:
List<float> Brazil = new List<float>();
Brazil.Add(1401620f);
Brazil.Add(3.1f);
Brazil.Add(200.03f);
Brazil.Add(1);
Brazil.Add(1);
List<float> Argentina = new List<float>();
Argentina.Add(406677f);
Argentina.Add(1);
Argentina.Add(1);
Argentina.Add(1);
Argentina.Add(1);
countryValuesDictionary.Add("Brazil", Brazil);
countryValuesDictionary.Add("Argentina", Argentina);
}
Thank you
Comment
Answer by RGS-Aaron · Mar 13, 2017 at 12:22 AM
Lists are classes you need to create an instance with the new keyword before you can use them.
public static Dictionary<string, List<float>> countryValuesDictionary;
To
public static Dictionary<string, List<float>> countryValuesDictionary = new Dictionary<string, List<float>>();