I have a code that randomly spawn enemies. How can i make so that the enemies spawed dont repeat?
The code goes like this
IEnumerator SpawnWaves ()
{
yield return new WaitForSeconds (startWait);
while (true) {
for (int i = 0; i < hazardCount; i++) {
platform = Random.Range (1, 4);
switch (platform) {
case 1:
Instantiate (prefab1, new Vector3 (0, 6, 0), Quaternion.identity);
break;
case 2:
Instantiate (prefab2, new Vector3 (0, 6, 0), Quaternion.identity);
break;
case 3:
Instantiate (prefab3, new Vector3 (0, 6, 0), Quaternion.identity);
break;
}
if (!dead) {
yield return new WaitForSeconds (Random.Range (spawnWaitStart, spawnWaitEnd));
}
if (dead) {
yield return new WaitForSeconds (100);
}
}
}
}
Thank you!
Well if Answers can stay up long enough I’ll post this (4th attempt!).
This is just example code but it stores a List of three numbers and removes the one picked. When it gets to 0 it rebuilds the list. Only an example so if you can’t work out what to do with the list let me know.
using UnityEngine;
using System.Collections;
using System.Collections.Generic; // IMPORTANT ADD THIS TO USE LISTS
public class ListTest : MonoBehaviour {
private List<int> EnemyCountList = new List<int>();
private int myInt;
// Use this for initialization
void Start () {
LoadEnemyList();
}
// Update is called once per frame
void Update () {
myInt = Random.Range (0,EnemyCountList.Count);
Debug.Log ("How many in the list = " + EnemyCountList.Count + " Selected Int = " + EnemyCountList[myInt]);
// instantiate your enemy your enemy number is EnemyCountList[myInt];
EnemyCountList.Remove(EnemyCountList[myInt]);
if(EnemyCountList.Count == 0)
LoadEnemyList();
}
void LoadEnemyList()
{
EnemyCountList.Add(1);
EnemyCountList.Add(2);
EnemyCountList.Add(3);
}
}
EDIT
OK so you just don’t want the same one as last time but any other order is OK?
private int lastLoaded = 0;
// after platform = Random.Range(1,4)'
if(platform == lastLoaded)
int tempRand = Random.Range(0, 2);
switch (platform) {
case 1:
if(tempRand = 0)
platform = 2;
else
platform = 3;
break;
case 2:
if(tempRand = 0)
platform = 1;
else
platform = 3;
break;
case 3:
if(tempRand = 0)
platform = 1;
else
platform = 2;
break;
}
// after you instantiate the object
lastLoaded = platform;
add that and it should stop the previous enemy from instantiating, not tested that code though so watch for errors.
Just keep track of what the last one was, and re-randomise if you pick it again next time.
int lastPlatform=-1;
while (true)
{
for (int i = 0; i < hazardCount; i++) {
platform = Random.Range (1, 4);
while (platform == lastPlatform)
{
platform = Random.Range(1,4);
}
lastPlatform = platform;
switch (platform) {
// rest of it as in the question.