Array Null Help?

Hi all! I’m trying to figure out why it is so difficult to check if all objects in the inspector array are gone/null/collected.

var Gameobject : GameObject[];

function Update(){
	foreach(GameObject in Gameobject){
		if(Gameobject == 0){
			Debug.Log("All are null!");
		}
	}
}

I’ve read all the Unity docs but they don’t help in this case. Now, Unity doesn’t recognize foreach. I’m using 4.2.
The array is simple. I put the size as 5 and drag and drop my coins in each slot. How do I check if all those coins are null?

Thanks! :slight_smile:

To avoid errors try not to use System type key names in the foreach.

Try

if(gObject == null) {
  print(gObject.name);
}

That still doesn’t quite help. I’m trying to find out how I can detect if an array of GameObjects are empty.

I’m not sure what you’re trying to do exactly, but a few tips…

As previously stated, rename your array to something that’s not an existing type (maybe goArray[ ]);

Your “foreach” isn’t correct. It should be something like foreach (GameObject go in goArray) That is, you didn’t provide a name for the current object.

Are you trying to decide if the current object is null, or the array itself is empty? For the former, that should be if (go == null)For the latter, it’d be something like if (goArray != null goArray.Length > 0) { // We have items }

I’m trying to see if ALL objects in the array are empty/null when they are destroyed. Right now, this is what I have and the game doesn’t know what ‘go’ is. I thought it was a gameObject…guess not.

var go : GameObject;
var Objs : GameObject[];

function Start(){
	renderer.enabled = false;
}

function Update(){
	foreach(GameObject go in Objs){
		if(Objs != null  Objs.Length > 0){
			Debug.Log("Objects Collected!");
		}
	}
}

Look closely at what you’re comparing, this is why Black Mantis was recommending naming your variables better.

Objs is your array.

go is the element that you’re looking at inside the foreach loop. You need to check if go is null, not Objs.

Also you’re mixing .js and .cs, there is no foreach in .js

var Objs : GameObject[];

function Start(){
	renderer.enabled = false;
}

function Update(){
	var arrayEmpty : boolean = true;

	for (go : GameObject in Objs){
		if(go != null){
			arrayEmpty = false;
		}
	}

	if (arrayEmpty)
	{
		Debug.Log("Objects Collected!");
	}
}

That makes a bit more sense. I didn’t know foreach wasn’t in js. I may have to change the boolean statements to their opposites just to make a bit more sense, but this should work when I try it later. Thanks!

I still hardly, understand it, but…it works! Thanks! :smile: