- Home /
How To Select Random Enemy From Array
How would I select a random enemy from an array index. So far I have made this script that spawns all enemies from the array, instead of picking one random enemy from the array.
I can post more code if needed.
Code:
for(int i = 0; i < EnemyPrefab.GetLength(0); i++)
{
Vector3 offset = Random.onUnitSphere;
// Setting a value
offset.z = 0;
// Setting a value
offset = offset.normalized * SpawnDistance;
// Instantiating the Gameobject
GameObject go = (GameObject) Instantiate(EnemyPrefab[i], transform.position = offset, Quaternion.identity);
}
Answer by itsmealex100 · Apr 29, 2015 at 03:04 PM
Hi, you're almost there. Try this:
GameObject go = (GameObject) Instantiate(EnemyPrefab[Random.Range(0,5)], transform.position = offset, Quaternion.identity);
I have put random range to 0-5, you will need to change that to match however many enemies you have in your array
Answer by rageingnonsense · Apr 29, 2015 at 03:05 PM
EnemyPrefab[Random.Range(0, EnemyPrefab.Length)]
This will get you a random index.
Answer by bartm4n · Apr 29, 2015 at 03:05 PM
It's actually pretty straightforward. Most of the logic is the same, you just don't iterate through the entire array.
You would generate and store a random number between 0 and the length of your array-1 and then use that as the index when you instantiate your GameObject from the array.
Your answer
Follow this Question
Related Questions
Enemy moves randomly within a area. 1 Answer
Make AI walk around randomly until Player is Seen. (C#) 2 Answers
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
get enemy to chase and shoot at player wherever hes facing. 0 Answers