random target selection

I have a bunch of fighters flying around shooting at eachother and all that works fine except each side goes for whichever of the enemy is first on the hierarchy instead of picking a random target. how can i get it to randomly pick a target?

function Start()
{
     target = GameObject.Find("Fighter1").transform; //target the player
     print(""+target);

    }

function Update () {

if (target==null){
target=GameObject.Find("Fighter1").transform;
}

thanks!

2 Answers

2

Store an array of all the fighters. When selecting a fighter to target, generate a random int and than set the fighter to target the object in the array with that index.

how do i make an array though? thats where i'm getting hung up.

–

Give all the enemies on that side a particular tag... say, "foo". Then....

function Start() {
    var possibleTargets = GameObject.FindGameObjectsWithTag("foo");
    target = possibleTargets[Random.Range(0, possibleTargets.length)].transform;
}

on edit for people who look at it later all the enemies need to change to possibleTargets. other than that works like a charm! thanks!

–

Oopsy... Fixed.

–