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.


			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*, transform.position = offset, Quaternion.identity);*
  •  	}*

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

EnemyPrefab[Random.Range(0, EnemyPrefab.Length)]

This will get you a random index.

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.