- Home /
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!
Answer by sneftel · Apr 28, 2011 at 10:55 PM
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!
Answer by xCRKx TyPHooN · Apr 28, 2011 at 10:48 PM
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.