- Home /
Question by
shrutiturner · May 08, 2018 at 12:21 PM ·
c#xml
XML file data won't load - am I using the function incorrectly?
I'm trying to read in an xml file so that I can use the data within in my application.
I get the following error when I run my code: NullReferenceException: Object reference not set to an instance of an object levelHandler.LoadLevel (Int32 nr) (at Assets/Scripts/levelHandler.cs:41) turnManager.Start () (at Assets/Scripts/turnManager.cs:26)
I have tried to debug the code, and from what I gather, and the error is because I have a null array, therefore the "levString" line will not work.
Please could you tell me what I'm doing wrong?
using System.Collections;
using System.Collections.Generic;
using System.Xml;
using UnityEngine;
public class levelHandler : MonoBehaviour
{
XmlDocument levelDoc;
XmlNodeList levelList;
List<string> levelArray;
// Use this for initialization
void Start()
{
levelArray = new List<string>();
levelDoc = new XmlDocument();
TextAsset xmlFile = Resources.Load("levels", typeof(TextAsset)) as TextAsset;
levelDoc.LoadXml(xmlFile.text);
levelList = levelDoc.GetElementsByTagName("level");
foreach(XmlNode levelData in levelList)
{
XmlNodeList levelInfo = levelData.ChildNodes;
foreach(XmlNode data in levelInfo)
{
if(data.Name == "setup")
{
levelArray.Add(data.InnerText);
}
}
}
}
public void LoadLevel(int nr)
{
string[] levString = levelArray[nr - 1].Split(',');
foreach(string brick in levString)
{
GameObject.Find(brick).GetComponent<lightSwitch>().change();
}
}
// Update is called once per frame
void Update ()
{
}
}
Comment
Your answer
![](https://koobas.hobune.stream/wayback/20220612162244im_/https://answers.unity.com/themes/thub/images/avi.jpg)