FindClosestEnemy() change target?

Hi, i'm using the function I found in Unity Script Reference, about FindGameObjectWithTag.

Then I must be able to change between the targets tagged as "Enemy". How would i do in this code?:

function FindClosestEnemy () : GameObject {

var gos : GameObject[];
gos = GameObject.FindGameObjectsWithTag("Enemy"); 
var closest : GameObject; 
var distance = Mathf.Infinity; 
var position = transform.position; 

for (var go : GameObject in gos)  { 
    var diff = (go.transform.position - position);
    var curDistance = diff.sqrMagnitude; 
    if (curDistance < distance) { 
        closest = go; 
        distance = curDistance; 
    } 
    if (Input.GetButton("Jump")) {
        //What would i do here??? how?
    }
} 
return closest;    

}

The problem is that it is an array, and doesn't looks like an array, so then i don't know how to increment "gos[THIS]"....

Thank you so much! :D

Your question made sense right up until the end. It is an array and looks like one just fine. You can't increment a gameobject and you already are iterating through the array if that's what you were trying to convey.

What you've got there is a foreach loop. It iterates through every element in the array. it is essentially equivalent to

for (var i = 0; i < gos.length ; i++)
{
    var go = gos*;*
 *if(go)*
 *{*
 *//...the contents of your foreach loop*
 *}*
*}*
*```*
*<p>Your calculation of the closest enemy is fine except for the last if statement. Why are you trying to do something when you jump for every loop iteration? The if statement should not be inside your function at all let alone this loop.</p>*
*<p>I think you want something like:</p>*
*```*
*function FindClosestEnemy () : GameObject {*
 *var gos : GameObject[] = GameObject.FindGameObjectsWithTag("Enemy");* 
 *var closest : GameObject;* 
 *var distance = Mathf.Infinity;* 
 *var position = transform.position;* 
 *for (var go : GameObject in gos) {* 
 *if((go.transform.position - position).sqrMagnitude < distance) {* 
 *closest = go;* 
 *distance = curDistance;* 
 *}* 
 *}*
 *return closest;* 
*}*
*function Update()*
*{*
 *var target : GameObject = FindClosestEnemy();*
 *if (Input.GetButton("Jump")) {*
 *//Do whatever you want here.*
 *}*
*}*
*```*