Iterate trought gameobject array

I want to iterate trougth array of gameobjects and print their names to gui , i do have singleton object which has my array:

Singleton object:

public static var JobBuildings : GameObject[] = new GameObject[1];

I have this code to run trought gameobject array :

for (var Job : GameObject in Var.JobBuildings)  { 

				switch(Job.transform.name){
					case "Plant_Wheat" : 
					print(Job.GetComponent(Crops_Wheat_AI).WorkSlots);
					GUI.Label( Rect(10,10,250,80), "Available farm positions: " + Job.GetComponent(Crops_Wheat_AI).WorkSlots);
					break;
				}
			}

But i get this error and i don’t know why !
NullReferenceException: Object reference not set to an instance of an object
UserGui.OnGUI () (at Assets/Script/UserGui.js:75)

where is line 75?

Yeah we need to see the line in question. Also you really shouldn’t be calling a method from a nullable return type, you’re just asking for a NullReferenceException there.

Lol yeah… line 75 :
switch(Job.transform.name){

since when does a transform have a name?

i think you want Job.gameobject.name
or Job.name because it is a gameobject

I noticed that too just moment ago, still getting same error, could this be a bug in unity ?? I really can’t see what im doing wrong…

for (var Job : GameObject in Var.JobBuildings) { 
	//Do a simple null check.. Always good practice.
	if(Job != null) {
		switch(Job.transform.name) {
		    case "Plant_Wheat" : 
		    print(Job.GetComponent(Crops_Wheat_AI).WorkSlots);
		    GUI.Label( Rect(10,10,250,80), "Available farm positions: " + Job.GetComponent(Crops_Wheat_AI).WorkSlots);
		    break;
		}
	}
	else {
		Debug.Log("Our Object we are looping over is null")
	}
}

As an add-on to Adinac:

for (var Job : GameObject in Var.JobBuildings) { 
	//Do a simple null check.. Always good practice.
	if(Job != null) {
		switch(Job.transform.name) {
		    case "Plant_Wheat" : 
		    if(Job.GetComponent<Crops_Wheat_AI>() == null)
				break;
		    print(Job.GetComponent<Crops_Wheat_AI>().WorkSlots);
		    GUI.Label( Rect(10,10,250,80), "Available farm positions: " + Job.GetComponent<Crops_Wheat_AI>().WorkSlots);
		    break;
		}
	}
	else {
		Debug.Log("Our Object we are looping over is null")
	}
}

I always try and check whether the GameObject actually has the component you’re querying, before asking for members of that component.

Thank you, null check was great idea. But problem really was that my array were empty… It works now :slight_smile: