My implementation was slightly different from Rick’s. Rather than using an object reference, I just passed the randomized array index to SpawnEnemy() directly. It seems to work just fine.
public class EnemySpawner : MonoBehaviour
{
bool spawn = true;
[SerializeField] float minSpawnDelay = 1f;
[SerializeField] float maxSpawnDelay = 5f;
[SerializeField] Enemy[] enemyPrefabArray;
// Start is called before the first frame update
IEnumerator Start()
{
while (spawn == true)
{
yield return new WaitForSeconds(Random.Range(minSpawnDelay, maxSpawnDelay));
SpawnEnemy(SelectRandomEnemyIndex());
}
}
private int SelectRandomEnemyIndex()
{
int enemyIndex = Random.Range(0, enemyPrefabArray.Length);
return enemyIndex;
}
private void SpawnEnemy(int index)
{
Enemy newEnemy=Instantiate(enemyPrefabArray[index], transform.position, Quaternion.identity) as Enemy;
newEnemy.transform.parent= transform;
}
}