I need to access everything tagged as a “LoadBar” in my game, so I found all objects with the tag (FindObjectsOfType), and then used a foreach loop to add them all to a List of LoadBars.
This code returns a NullReferenceException the line before I (try to) print: "Did it work?
void Start () {
//print ("STARTING!");
GameObject [] loadObjects = GameObject.FindGameObjectsWithTag("LoadBar");
foreach (GameObject loadObject in loadObjects) {
print (loadObject.name + " exists and is NOT null");
if (loadObject.GetComponent<LoadBar> () == null) {
Debug.Log ("A GameObject tagged as a LoadBar isn't a loadbar. Fix it.");
} else {
print ("Found one 'o' 'dem LoadBars boss!");
loadBars.Add (loadObject.GetComponent<LoadBar> ());
print ("Did it work?");
loadObject.SetActive (false);
}
}
Thank you to anyone who can help.
Turns out I was very stupid, and forgot to initialize my List. If anyone else has a similar problem, remember: you have to initialize those variables.