- Home /
 
Error use of unassigned local variable
Hi,
i need to fill a array with a for loop for each item in an xml file.
Within in the forloop by the first line it's says "use of unassigned local variable items" I tried everything and cannot find a solution.
Anyways here the code:
 public Item[] loadXmlFile(string filename,string tagname)
     {
         Item[] items;
         TextAsset file;
         file = Resources.Load(filename) as TextAsset;
         XmlDocument xmlFile = new XmlDocument();
         xmlFile.LoadXml(file.text);
         XmlNodeList listNodes = xmlFile.GetElementsByTagName(tagname);
 
         for (int i = 0; i <= listNodes.Count; i++)
         {
             items[i].itemName = listNodes[i].Attributes["itemname"].Value;
             items[i].prefab = (Transform)Resources.Load(listNodes[i].Attributes["prefab"].Value);
             items[i].icon = (Texture2D)Resources.Load(listNodes[i].Attributes["icon"].Value);
             items[i].buildCost = listNodes[i].Attributes["buildcost"].Value;
             items[i].maxInhab = listNodes[i].Attributes["maxInhab"].Value;
             items[i].elecConsump = listNodes[i].Attributes["elecconsump"].Value;
             items[i].waterConsump = listNodes[i].Attributes["waterconsump"].Value;
             items[i].xpAdd = listNodes[i].Attributes["xpadd"].Value;
             items[i].itemText = listNodes[i].Attributes["itemtext"].Value;
         }
         return items;
     }
 
              Answer by 1337GameDev · Apr 05, 2013 at 04:12 PM
You should initialize the array with a specified number of elements.
Use: Item items[] = new Item[sizeHere];
Then you can populate the array.
Yes , that gets rid of the unassigned error now it gives me a null reference exception again at the same line (line 12) ("Object reference not set to an instance of an object). I feel dumb today i really have no clue whats going on here ?
Answer by Aria-Lliane · Apr 05, 2013 at 06:44 PM
Maybe I'm being silly but just like the error says "items" is not initialized?
 //this will be before the for loop
 items = new item[listNodes.Count];
 
 
               And by the way, since 'i' starts at 0 you dont go to "i<=listNodes.Count" but to "i< listNodes.Count" right?
Yes it comes before the for loop. if the array size is 5 and you use i=0 < then it will loop five times, if you use i=0
Your answer
 
             Follow this Question
Related Questions
rotating vertices with for loop in 0 Answers
GUI button image next 2 Answers
C# Killfeed issues 0 Answers
Array error, cannot convert float to float[] ???? 2 Answers
Where should I use a traditional forloop as opposed to 'for (var i in monsters)'? 1 Answer