- Home /
How to start coroutine after it gets stopped
Hey so im starting a coroutine when i start my game and when there is enough enemies I stop it and then I can click on a button to start spawning enemies again the coroutine wont start can someone help me? here is my script
public void NextWaveButton()
{
currentWaveNumber++;
maxNumberOfEnemies *= 2;
currentNumberOfEnemies = 0;
StartCoroutine (es);
nextWaveButton.SetActive(false);
}
IEnumerator SpawnRandomEnemy()
{
WaitForSeconds wait = new WaitForSeconds(spawnInterval);
while (currentNumberOfEnemies < maxNumberOfEnemies)
{
enemiesLeft = maxNumberOfEnemies;
int enemyIndex = Random.Range(0, enemyPrefabs.Length);
enemyRandomSpawnPoint = Random.Range(0, spawnPoints.Length);
GameObject newEnemy = Instantiate(enemyPrefabs[enemyIndex], spawnPoints[enemyRandomSpawnPoint].transform.position, enemyPrefabs[enemyIndex].transform.rotation);
newEnemy.transform.parent = enemyContainer.transform;
currentNumberOfEnemies++;
yield return wait;
}
if (currentNumberOfEnemies == maxNumberOfEnemies)
{
Debug.Log("Max number of enemies spawned so stopped spawning more enemies");
StopCoroutine(es);
}
}
Answer by SandorChickane · Apr 07, 2020 at 03:37 PM
Are you ever reducing the 'currentNumberOfEnemies' variable (presumably when they're killed)? Otherwise when you re-start the coroutine it might immediately stop again because that variable still says you're at the maximum number of enemies.
Yes when i click the nextwavebutton it sets the currentNumberOfEnemies to 0
Where you're calling StartCoroutine(es), it might be that 'es' loses its reference to this coroutine after the first time you stop it. Ins$$anonymous$$d of calling 'StartCoroutine(es)' in the NextWaveButton function, try 'es = StartCoroutine(SpawnRandomEnemy())' ins$$anonymous$$d
Your answer
Follow this Question
Related Questions
Wave Spawning not working 1 Answer
Enemies spawn on top of each other(C#)(Unity) 1 Answer
Script that allows me to spawn enemies in game. 1 Answer
Round control and enemy control issues - Javascript 0 Answers
How to start another Coroutine after a specific condition is met while another Coroutine is running? 1 Answer