0

In Unity3D I am trying to loop through all the components on an object and get their variables and values. This is the code that keeps throwing the exception:

componentvariables = new ComponentVars[component.GetType().GetFields().Length];
int x = 0;
//Get all variables in component
foreach(FieldInfo f in component.GetType().GetFields()){
    componentvariables[x]=new ComponentVars();
    componentvariables[x].Vars.Add(f.Name,f.GetValue(component).ToString());
    x++;
}

The ComponentVars class is

public class ComponentVars{
    public Dictionary<string, string> Vars{get;set;}
}

Yes I know it is very simple and I could just use an array of dictionaries but I plan on adding more to it later.

The part that keeps throwing the error is

componentvariables[x].Vars.Add(f.Name,f.GetValue(component).ToString());

I usually see these where a variable is not initialized but I have tried initializing it (as seen in the code above) and I still continue to get a NullRefEx.

Can anyone see what I am doing wrong here?

John Saunders
  • 160,644
  • 26
  • 247
  • 397
  • Properties aren't initialized automagically.. you have to do it. So as @p.s.w.g stated, initialize your `Vars` property. – Simon Whitehead Dec 18 '13 at 04:29
  • Thanks Simon, I just overlooked that, it's always the simple things I miss. – Ernest Mallett Dec 18 '13 at 04:45
  • possible duplicate of [What is a NullReferenceException and how do I fix it?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – CodeSmile Feb 16 '15 at 10:49

1 Answers1

2

Make sure you initialize your Vars dictionary before you try to add a value to it:

foreach(FieldInfo f in component.GetType().GetFields()){
    componentvariables[x] = new ComponentVars();
    componentvariables[x].Vars = new Dictionary<string, string>();
    componentvariables[x].Vars.Add(f.Name, f.GetValue(component).ToString());
    x++;
}

Or even better, initialize it in the class:

public class ComponentVars{
    public Dictionary<string, string> Vars { get; private set; }

    public ComponentVars()
    {
        this.Vars = new Dictionary<string, string>();
    }
}
p.s.w.g
  • 146,324
  • 30
  • 291
  • 331