- Home /
[Answered] NullReference problem with dictionary
Hi,
I'm having issues dealing with a dictionary that I want to use to keep track of what dialog has been said.
In both cases, the key doesn't exist in the dictionary. When I do this, things are fine.
void Start(){
Dictionary<int, string> saidDialogs = new Dictionary<int, int>();
saidDialogs.TryGetValue(dIndex, out dictResult);
}
But when I do this, I get constant NullReferenceExceptions:
void Start(){
Dictionary<int, int> saidDialogs = new Dictionary<int, int>();
}
void Update(){
CheckForDialog();
}
void CheckForDialog(){
saidDialogs.TryGetValue(dIndex, out dictResult);
}
Any idea why?
Answer by Wuzseen · Feb 16, 2014 at 10:20 PM
Your dictionary should be a member of the class.
class DialogThing {
Dictionary<int, int> saidDialogs;
void Start() {
saidDialogs = new Dictionary<int,int>();
}
}
Basically the rest as you've got it should be fine from what I can see.
Answer by kathode · Feb 16, 2014 at 10:33 PM
Ah thanks. Looks like the problem was that I was declaring the dictionary as a class member, and then in Start(), redeclaring it with "Dictionary saidDialogs = new Dictionary();"
Once I removed that "Dictionary" from the second part, things started working.
Thanks so much for all the help!
Your answer

Follow this Question
Related Questions
Unable to use global Dictionary in function. "NullReferenceException" 1 Answer
Adding keys to a static Dictionary doesn't keep the values at the end of the function 1 Answer
Static Dictionary not initializing properly 1 Answer
Allocating Game Object name dynamically using Find 0 Answers
NullReferenceException 1 Answer