Array index targetting doesn't work

Hi all

I’m working on a targetting system. but it will only select the last element of the array.
Here is my code:

var target : Transform;
var angle : float;
var avTargets : Array = new Array();
var index : int = 1;

function Start () {
}

function Update () {
if(PlayerStates.currentState == CharStates.combat){
if(Input.GetKeyUp(KeyCode.Mouse0)){
Attack();
SearchForTargets();
}
}
Debug.Log(avTargets);
}
function Attack(){
//angle = Vector3.Dot((target.position - this.transform.position).normalized,transform.forward);

}


function SearchForTargets(){
avTargets.clear();
var curArray : Array = new Array(GameObject.FindGameObjectsWithTag("Enemy"));
for (var curObj : GameObject in curArray ){
for( var i = 0; i < curArray.length; i++){
avTargets *= curObj.transform;*

}
}
ToggleIndex();
}

function ToggleIndex(){
if(index < avTargets.length - 1){
index++;
}
else if(index >= avTargets.length - 1){
index = 0;
}
SelectTarget();

}
function SelectTarget(){
//if(target != null){
//target.GetComponent(Enemy).isTarget = false;
//}
target = avTargets[index];
//target.GetComponent(Enemy).isTarget = true;

}
I hope that someone can help me :slight_smile:

On lines 27-31 of your code, you go through the array of targets, and assign the transform of each target to every index of avTargets, the result is that each new target over-writes all the old ones, and you end up with all the transforms in avTargets pointing to the last target. Fixed code would be something like this:

function SearchForTargets(){
avTargets.clear();
var curArray : Array = new Array(GameObject.FindGameObjectsWithTag("Enemy"));
var i = 0;
for (var curObj : GameObject in curArray ){
avTargets[i++] = curObj.transform;
}
ToggleIndex();
}

which assigns each target’s transform to only one index in avTargets. Note both the var i decleration on line 4 and the i++ on line 6.

Hope this helps.