- Home /
target and look at random enemies
I'm not exectly sure on how to have an object look at a random target. I know i have to use the
LookAt(target);
or something like that. But the things i want it to target all have the same name. They are all named "Enemy(Clone)". How do I make the object look at a random enemy when they all have the same name?.
Answer by GesterX · May 11, 2011 at 10:07 PM
Use FindGameObjectsWithTag. Make sure you have all your enemies tagged and then do something like this...
//an array of gameObjects var enemies : GameObject[]; //the target var theTarget : GameObject;
var rand;
//a function to look at a random enemy function LookAtRandomEnemy(){ //fill the array with all gameobjects tagged with Enemy enemies = GameObject.FindGameObjectsWithTag("Enemy");
//A random number between 1 and the number of enemies rand = Random.Range(1, enemies.Length)
//set the target as the enemy at the position rand in the array theTarget = enemies[rand];
//look at the target LookAt(theTarget); }
Now just call this when you want to look at a random enemy.
Using a random number between 1 and the array length would miss the first element. Use... rand = Random.Range(0, enemies.Length()); ...ins$$anonymous$$d
Your answer
Follow this Question
Related Questions
Removing objects from an array 2 Answers
Target distance would only update closer 1 Answer
FindClosestEnemy() change target? 1 Answer
Cannot cast from source type to destination type 1 Answer
inspector,Component 0 Answers