[Code Attached] Targetting enemys randomly

Trying to target an enemy and when the mouse button is pressed it switches to another target close to me.
Think I’m on the right lines but not sure where i’m going wrong…

var enemies : GameObject[];
var rand;

function LookAtRandomEnemy(){
if (Input.GetButtonDown ("Fire1")){
    enemies = GameObject.FindGameObjectsWithTag("Enemy");
        rand = Random.Range(1, enemies.Length);
        theTarget = enemies[rand];

        LookAt(theTarget);
    }
}

At the very least, your Random.Range arguments are off by one. You’d want:

rand = Random.Range(0, enemies.Length - 1);

Though, you should probably verify that the enemies array has content prior to accessing it.

Jeff

If I remember correctly, the second parameter was not included in the random generation so the length check was fine

Yeah, you’re right. While the FLOAT version of Random.Range is inclusive of the max parameter, the INT version of Random.Range is exclusive of the max parameter. So, the correct code would be:

rand = Random.Range(0, enemies.Length);