Calling StopCoroutine doesnt work. I have a script that spawns object and I want it to stop once game over happens. But the object keeps spawning even after the game gets over.
This is the spawn script.
public GameObject object;
void Start () {
StartSpawn ();
}
void Update () {
}
public void StartSpawn(){
StartCoroutine("SpawnObj");
}
public void StopSpawning() {
StopCoroutine("SpawnObj");
}
IEnumerator SpawnObj()
{
Instantiate(object, new
Vector3(transform.position.x,transform.position.y,0), Quaternion.identity);
yield return new WaitForSeconds(Random.Range(1f, 1.5f));
StartCoroutine("SpawnObj");
}
}
This is the script that calls the stopspawn function.
public void GameOver(){
gameOver = true;
GameObject.Find("Spawnerwithtime").GetComponent<Spawnerwithtime> ().StopSpawn();
} // Spawnerwithtime is the name of the spawn script
Thank You!
Hi SonicDirewolf,
First of all, your code won’t work because your stopping function is named StopSpawning and you are calling instead StopSpawn. Also, your SpawnObj function should be public to be accessed from another script.
Secondly, you are starting another coroutine from your coroutine and lose your reference to your first coroutine.
You can instead use a while loop with a boolean flag that will do the same job without spawning lots of coroutines and losing references.
This code will work better for you:
public GameObject object;
private bool shouldSpawn = false;
void Start () {
StartSpawn ();
}
void Update () {
}
public void StartSpawn() {
shouldSpawn = true;
StartCoroutine(SpawnObj());
}
public void StopSpawning() {
shouldSpawn = false;
}
public IEnumerator SpawnObj() {
while(shouldSpawn) {
Instantiate(object, new Vector3(transform.position.x,transform.position.y,0), Quaternion.identity);
yield return new WaitForSeconds(Random.Range(1f, 1.5f));
}
}