I want to spawn random prefabs, but I don't want to have any of them coincidentally be identical. I currently have this code block:
int animalIndex = Random.Range(0, 8);
int animalIndex2 = Random.Range(0, 8);
int animalIndex3= Random.Range(0, 8);
int animalIndex4 = Random.Range(0, 8);
int animalIndex5 = Random.Range(0, 8);
int animalIndex6 = Random.Range(0, 8);
// spawn first card
GameObject breeder1 = Instantiate(breedingPhase.randomPrefabs[animalIndex], new Vector3(-4.5f, 3.2f, 0), Quaternion.identity);
// spawn second card
GameObject breeder2 = Instantiate(breedingPhase.randomPrefabs[animalIndex2], new Vector3(0, 3.2f, 0), Quaternion.identity);
// spawn third card
GameObject breeder3 = Instantiate(breedingPhase.randomPrefabs[animalIndex3], new Vector3(4.5f, 3.2f, 0), Quaternion.identity);
// spawn fourth card
GameObject breeder4 = Instantiate(breedingPhase.randomPrefabs[animalIndex4], new Vector3(-4.5f, -2, 0), Quaternion.identity);
// spawn fifth card
GameObject breeder5 = Instantiate(breedingPhase.randomPrefabs[animalIndex5], new Vector3(0, -2, 0), Quaternion.identity);
// spawn sixth card
GameObject breeder6 = Instantiate(breedingPhase.randomPrefabs[animalIndex6], new Vector3(4.5f, -2, 0), Quaternion.identity);
Using the code block above, I can spawn random animals but there are instances where some of them are the same prefab. Thank you in advance for your replies.
You can make a copy of the prefab array and randomly shuffle the elements. Since their order will be random you can simply pick the first, second, etc. element and instantiate it, thus guaranteeing that there will be no duplicates.
The following code shuffles the prefabs by going thru the array element by element and swapping each with another element from the array. An element can also be swapped with itself. I've "lazyfied" your code a little to remove the repetition. It will spawn breeders depending on how many positions are specified.
Note that this code will cause an error if you specify more positions than prefabs.