Search code examples
unity-game-engineunityscript

Skip add to array


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

var enemies : GameObject[];

function Start(){
    seeEnemies();
}

function seeEnemies():GameObject{
    enemies = GameObject.FindGameObjectsWithTag("enemy");
}

Example:
Enemy 1 has an array which has Enemy 2,3,4.
Enemy 2 has an array which has Enemy 1,3,4.
Enemy 3 has an array which has Enemy 1,2,4.
Enemy 4 has an array which has Enemy 1,2,3.


Solution

  • Probably skipping the add is more expensive than simply adding all, and removing the object afterwards.

    You could also work with indirection: each object 'knows' it's index in the array. When iterating the array, you skip 'your own' index:

    var what_to_do = function( index, element ) {
       // do stuff with element
    }
    // handle all elements _before_ this
    var i = 0;
    for( ; i != this.index && i != elements.length; ++i ) {
      what_to_do( i, elements[i] );
    }
    ++i; // skip this one
    for( ; i < elements.length; ++i ) {
      what_to_do( i, elements[i] );
    }
    

    The 'do stuff' may be encapsulated in an anonymous function, in order not to have to repeat yourself.

    -- EDIT --

    Hmmm... and you may even factor out the 'skip' function:

    function skip_ith( elements, thisindex, f ) {
       var i = 0; 
       for( ; i != thisindex && i != elements.length; ++i ) {
          f( i, elements[i] );
       }
       ++i;
       for( ; i < elements.length; ++i ) { // note: < because i may be length+1 here
          f( i, elements[i] );
       }
    }
    

    Application:

    for( var i = 0; i != elements.length; ++i ) {
       skip_ith( elements, i, function( index, element ) {
          // do stuff with element
       } );
    }