null objects

I am totally confused, I want to let my script know, is there enemy in the scene?
Here is what I’m trying to use

var enemy : GameObject[];

function Update () {
	enemy  = GameObject.FindGameObjectsWithTag ("Enemy");	
	
        if(enemy == null){
	print ("there is no enemy");
	}
	
	if (enemy != null){
	print ("there is enemy somewhere");
	}
}

but it’s always print me “there is enemy somewhere” even if there is no…

Try printing out the contents of the enemy array?

It’s just a supposition but I guess the method returns an empty array which is quite different from null.
You should check the length of the Array instead of testing if enemy is null.

How to do that?

var enemy : GameObject[];
var enemyArray = new Array();

function Update () {
	enemy  = GameObject.FindGameObjectsWithTag ("Enemy");	
	enemyArray.Add (enemy);
//	print (enemyArray);
	if(enemyArray == null){
	print ("there is no enemy");
	}
	
	if (enemyArray != null){
//	print (enemy);
	print ("there is enemy somewhere");
	}
}

got the same…

enemy = GameObject.FindGameObjectsWithTag("Enemy");
if (enemy.Length > 0) {
    // do something
}

Ok, this is works too:

function Update () {
	enemy  = GameObject.FindGameObjectsWithTag ("Enemy");	
	enemyArray.Add (enemy);
	enemyArray.length = enemy.Length;
//	print (enemyArray.length);
	if(enemyArray.length <= 0){
	print ("there is no enemy");
	}
	
	if (enemyArray.length > 0){
//	print (enemy);
	print ("there is enemy somewhere");
	}
}

thx all

FindGameObjectsWithTag returns a GameObject[ ] so there’s no need for another array on top of that. Just check if the length of enemy is greater than 0. If it is, then you have enemies in your scene.

The docs seem to need this updated. I quote, “Returns null if no GameObject was found.” I don’t know where to start looking for a way to “report a bug” about the documents.

The bug reporter app.

–Eric

Thank you Eric5h5. I should have thought of that. It has been reported.