开发者

Skip add to array

开发者 https://www.devze.com 2023-02-28 01:26 出处:网络
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 ha

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开发者_StackOverflow中文版 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.


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
   } );
}


public class s_foo : MonoBehaviour {
public GameObject[] OrbitingSatellites = new GameObject[7];
public GameObject orbital1; // drag-dropped "small explosion" in Editor.

void Start() {
    OrbitingSatellites[0] = orbital1;
    Debug.Log("os = " + OrbitingSatellites[0].name); // prints "small explosion"
}

}

This is a correct method for adding game objects to a gameobject array, my problems lie elsewhere.

0

精彩评论

暂无评论...
验证码 换一张
取 消