I’ve seen a few threads about this (e.g. this), but the answers they provide don’t seem to work for me.
I’ve created a new project, and I have an Empty GameObject sitting in the scene, which I’ve named Controller. Attached to Controller are two C# Scripts: ControllerScript and LoadXML. My goal is to have ControllerScript import XML data and build the scene programmatically instead of me having to muck around in the editor by hand. To accomplish the “import XML data” part, I’m attempting to reference LoadXML within ControllerScript–like so:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class ControllerScript : MonoBehaviour {
public LoadXML xmlLoader;
List<string> cardNames;
// Use this for initialization
void Start () {
buildCardLibrary ();
}
void buildCardLibrary () {
Debug.Log ("running buildCardLibrary()");
xmlLoader = GameObject.FindObjectOfType(typeof(LoadXML)) as LoadXML;
Debug.Log (" ran FindObjectOfType looking for LoadXML class; xmlLoader = " + xmlLoader );
xmlLoader.loadXMLFrom("cards.xml");
}
// Update is called once per frame
void Update () {
}
}
As you can see, I declare xmlLoader as a public variable of type LoadXML at the top of the class, then set it using FindObjectOfType() within buildCardLibrary(). According to Debug.Log, once that happens, xmlLoader is an Object. However, I then get a NullReferenceException error when I attempt to run xmlLoader.loadXMLFrom(“cards.xml”). Unity says that the Object reference is not set to an instance of an object. I’ve tried replacing the xmlLoader = GameObject.FindObjectOfType(typeof(LoadXML)) as LoadXML line with
xmlLoader = GameObject.GetComponent<LoadXML>();
but this does not resolve the issue.
I’m obviously missing something here, but what?