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?