- Home /
NullReferenceException when trying to load XML
I can't figure out why this is throwing a NullReferenceException when I attach it to a gameobject.Any Help would be greatly appreciated.
enter code here
var available_Units : Array = Array();
var unitList : Array = Array();
private var UNIT_DATA : String = "unitData.xml";
function Start(){
LoadUnitsToArray();
}
function LoadUnitStats(unitID){
var asset : TextAsset = Resources.Load(UNIT_DATA);
var xmldoc : XmlDocument = XmlDocument();
xmldoc.LoadXml(asset.text);
var statArray = Array();
var SEARCH_STRING : String = "/player/unit[@id = '" + unitID + "']";
if (xmldoc != null){
var unit : XmlNode = xmldoc.SelectSingleNode(SEARCH_STRING);
var unitAttrib : XmlNodeList = unit.ChildNodes;
for(var i in unitAttrib){
statArray.Add(i.FirstChild.InnerText);
}
}
else
Debug.LogError("No XML data File Found");
return statArray;
}
function LoadUnitsToArray(){
var asset : TextAsset = Resources.Load(UNIT_DATA);
var xmldoc : XmlDocument = XmlDocument();
xmldoc.LoadXml(asset.text);
var allUnits = xmldoc.GetElementsByTagName("unit");
if (xmldoc !=null){
for (var i in allUnits){
var baseUnitStats : Array = LoadUnitStats(i);
available_Units.Add(baseUnitStats);
}
}
}
Would probably help if you told us where you were getting the null reference exception. There's lots of code here which is not exactly unity-standard, and I'm really not sure what bits might be causing the problem!
Yeah, that probably would help huh? Its says the exception occurs at the xmldoc.LoadXml(asset.text); line. Also, if it seems like I'm doing this in an awkward manner any suggestions are more then welcome.
Well, that suggests that the line where you assign 'asset' is returning null! Put some Debug.Logs in there, see if you can track down exactly where it's going wrong. Try using the explicit type version of Resources.Load-
var asset : TextAsset = Resources.Load(UNIT_DATA, TextAsset);
Also, reading the documentation, I think it explicitly states that extensions are omitted! Which means you should strip the '.xml' from the end there.
Thank you very much, removing the .xml extenstion did the trick. Also, I had to change the for loop in LoadUnitsToArray to for (i = 0; i < allUnits.Count; i++) since it was passing a element not an int.
Answer by DaveA · Nov 13, 2011 at 05:36 PM
From syclamoth: "strip the ".xml" extension from the end there"
Your answer
Follow this Question
Related Questions
How to check the path on Android 0 Answers
Xml Loading Issue 1 Answer
A node in a childnode? 1 Answer
Convert XML Deserializer from folder to resources 2 Answers
XML Error on Load 1 Answer