- Home /
null reference exception when I already checked if this was null
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.
@foureyes44 loadBars.Add
this one is null.
I dont see any reference of loadBars in your script.
Tips: stop using print();
use Debug.log()
. It is more practical.
@TheWorstUsername Oh, the loadBar List is in this script. I just didn’t think it was too important to put it here.
But while thinking about that, it re$$anonymous$$ded me that I probably didn’t initialize it. Do you think that could be the source of the problem?
@foureyes44 It surely is, seems like the only var who can not to be declared in there (next time, check it before asking if it's releated to the issue)
Answer by foureyes44 · May 12, 2018 at 05:18 AM
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.