Skip add to array

I know that with continue you can skip certains parts of scripts. But is there a way to do the same thing with an array. For example: I want that every object is stored in an array, but not the object(wich also has the same tag) wich wears this script.

  var enemies : GameObject[];

    function Start(){

        seeEnemies();

    }

    function seeEnemies():GameObject{

        enemies = GameObject.FindGameObjectsWithTag("enemy");

    }

Thanks in advance :)

1 Answer

1

You can leverage the continue keyword you were talking about earlier to do that, just remember it's not the only solution...

Instead of just using the array returned from FindGameObjectsWithTag, you can create your own array and insert into that array only the instances you want.

For example

var filteredEnemies: Array;

enemies = GameObject.FindGameObjectsWithTag("enemy");
for (var currEnemy in enemies)
{
    if (currEnemy.GetComponent(YourScriptName))
        continue;

    filteredEnemies.Add(currEnemy);
}

I hope I understood your question correctly...

So change the check from 'if (currEnemy.GetComponent(YourScriptName))' to 'if(currEnemy == gameObject)'. Simples.

Why would another object be added? GameObject.FindGameObjectsWithTag("enemy") should return only game objects that are tagged as "enemy"... And then you filter THOSE objects further by not adding the ones that have this script. So you should end up with an array of all the game objects in your scene that are tagged as "enemy" and don't have the script on them. Am I missing something?