NullReferenceException: Object reference not set to an instance of an object

I'm having a weird problem with Unity..

I have an array of references(is that even right?) to real objects in my scene and would the like to access a value, inside a script, attached to each of these objects. GameObject[] levelBuildings = GameObject.FindGameObjectsWithTag("BaseBuilding");

Later on, in another method I have this:

Debug.Log("Attempting to delete " + levelBuildings*.name);*
Debug.Log(levelBuildings*.GetComponent().nTestInt);*


…the first line works just fine and returns me the name of the building prefab, the seconds however throws an error “NullReferenceException”, which is weird, because checking in the editor that particular building in the editor has the script attached to it and has the nTestInt set to 5.


If I attach the same script to another empty game object and
GenericBuildingInteractionScript script = GameObject.Find(“scriptContainer”).GetComponent();
Debug.Log(script .nTestInt);


that works fine… I don’t really get what the difference and thus the issue is! Both of these are game objects, both of them have exactly the same script attached in the same way to them. The only difference is that I’m using an array to store references to the existing building objects in the first case…


Any ideas anyone?

Either levelBuildings *is null or points to a destroyed object, or what it does point to does not have the script you're looking for.

* *

Try adding

* *```* _if ( levelBuildings *) {*_ _*// do your stuff*_ _*} else {*_ _*Debug.Log("Error - null level building: " + i );*_ _*}*_ _*```*_ _*

And see if that helps you track down the problem.

*_