Hello everyone.
First of all, I would like to tell that I (think) I know what this “NullReferenceException: Object reference not set to an instance of an object” means and I know what causes it. But this is actually preety weird :S.
In my script, I’m using the XmlDocument class (from the .NET framework) to parse an external xml database. I’ve got a method, which returns a custom class made by me called Item, and I’ve got another method (both methods are public and non-static) which returns nothing (it’s void).
In the Item method, as well as in the void method, I declare an XmlNode field which points to the root node of my xmldocument, and then from there access any data I need from my Xml document.
That works just fine in my void function, but in my Item function, when I do exactly the same, for example:
int number = Convert.ToInt16(root.ChildNodes[0].InnerText);
I keep getting the NullRefferenceException. And I don’t know what I could be missing.
But what’s weird about this, is that I can even use Debug.Log() to print values from that xml database to the console. The values get printed and are just ok (I check my xml file and are correct), but the debug.log() throws a nullRefferenceException, even though the values actually get printed in to the console. If there’s a return value, and what I’m trying to print is of course an instance of a class, why could I be getting that nullRefferenceException? I’m actually refferncing a property from an instance of an object, and that same line is working inside another method in this same script (in the same class). I don’t know what’s wrong :S or what I could be missing…
Any help would be much appreciated
IMPORTANT EDIT: Ok, I think I’ve isolated a lot more the problem, the method is just right, the problem is when I call it from inside a foreach loop, like this:
foreach(XmlNode n in root.ChildNodes[ID-1].ChildNodes[7]){
itemList.Add (GetItem (Convert.ToInt16(n.InnerText), 1));
}
root is the root node of my XML document, itemList is a list of items I’m creating, and I don’t think there any other variable which I’ve made myself in this code that needs to be explained. Well, GetItem is the method which is causing trouble (it returns an instance of “Item”), it takes two integers as arguments.