Why aren't Coroutines working for me?
Hi, I was originally using InvokeRepeating for my enemies to spawn and it is fine if they spawn at a continuous rate but I want them to spawn faster and faster as the game goes on but since InvokeRepeating only happens on Start the variable spawnTime that decreases bit by bit doesnt change in the game.
I then researched and made it into a Coroutine that does what I need it to but if I start my Coroutine in Start only one enemy spawns right at the start and if i StartCoroutine in Update it spawns every frame.
There must be something wrong with my code but I have been scrutinising it four hours and can't find what is wrong.
Could you please help me locate the issue? I bless these problems since they are helping me to learn a lot more but when I need help I need help.
public GameObject enemy;
public float spawnTime;
public Transform[] spawnPoints;
void Start () {
StartCoroutine ("SpawnRepeat");
InvokeRepeating ("ChangeRate", 30, 30);
}
IEnumerator SpawnRepeat(){
Spawn ();
yield return new WaitForSeconds(spawnTime);
}
void Spawn(){
int spawnPointIndex = Random.Range (0, spawnPoints.Length);
Instantiate (enemy, spawnPoints [spawnPointIndex].position, spawnPoints [spawnPointIndex].rotation);
}
void ChangeRate(){
spawnTime -= 10f;
}
bool _spawnDone = true;
IEnumerator SpawnRepeat()
{
_spawnDone = false;
Spawn();
yield return new WaitForSeconds(spawnRate);
_spawnDone = true;
}
void Update()
{
if (_spawnDone)
StartCoroutine(SpawnRepeat());
}
Of course there are several ways that can go wrong , a StopCoroutine for example called while this coroutine is running will prevent SpawnRepeat() to run again but if you don't stop it in that way it should work.
Answer by voncarp · Feb 16, 2017 at 07:25 PM
Make it loop:
IEnumerator SpawnRepeat(){
for (;;) {
Spawn ();
yield return new WaitForSeconds(spawnTime);
}
}
Your answer
![](https://koobas.hobune.stream/wayback/20220612111248im_/https://answers.unity.com/themes/thub/images/avi.jpg)