This question was
closed Mar 26, 2017 at 11:41 AM by
hexagonius for the following reason:
Question by
$$anonymous$$ · Mar 26, 2017 at 09:52 AM ·
c#xmlnull reference exception
NullReferenceException with XML Deserializer
Hi, I'm new to unity and c# and lately i've been messing around with XML, but i keep having "NullReferenceException" when trying to load my file. I've tried to google it but can't find someone with the same error, i guess i made a mistake.
I hope you can help me. Thank you.
Here is my code, the line where the error occurs is commented.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Xml;
using System.Xml.Serialization;
using System.IO;
public class XMLManager : MonoBehaviour {
public static XMLManager ins; //Crappy Singleton (but hey! It works)
public Transform CastleParent;
void Awake(){
ins = this;
LoadItems ();
}
public ItemDatabase itemDB; //The Database of items
//Save Function
public void SaveItems(){
//open new XML File
XmlSerializer serializer = new XmlSerializer(typeof(ItemDatabase));
FileStream stream = new FileStream (Application.dataPath + "/StreamingAssets/castles_data.xml", FileMode.Create);
serializer.Serialize (stream, itemDB);
stream.Close ();
Debug.Log ("Item Saved Successfully");
}
//Load Function
public void LoadItems(){
//Load the XML File
XmlSerializer serializer = new XmlSerializer(typeof(ItemDatabase));
FileStream stream = new FileStream (Application.dataPath + "/StreamingAssets/castles_data.xml", FileMode.Open);
itemDB = serializer.Deserialize (stream) as ItemDatabase; //The Error occurs HERE!
stream.Close ();
Debug.Log ("Items Loaded");
}
}
[System.Serializable]
public class ObjectEntry {
public string itemName;
public Sprite spriteRef;
public Vector2 position;
public int SpriteLayer;
public Vector3 scale;
}
[System.Serializable]
public class CastleEntry {
public List<ObjectEntry> ObjectList = new List<ObjectEntry> ();
}
[System.Serializable]
public class ItemDatabase{
public List<CastleEntry> CastleList = new List<CastleEntry>();
}
Comment