[C#] Coroutine just won't stop!
Good evening!
I've encountered a wall, I might need help. Here it is: I want my to be in total control of what my IEnumerator is doing right there and for that I need to be able to stop the Coroutine but for some reason it just won't stop when I want it to.
The script bellow is just one of many test I've done and none are successful. Maybe IEnumerator is not the way to go? What are your thought??
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BackgroundControllerFast : MonoBehaviour
{
public GameObject[] landscapes;
public Vector3 spawnValues;
public int landscapeCount;
public float startWait;
public float spawnRate;
public float waveWait;
void Update()
{
bool down = Input.GetKeyDown("r");
bool up = Input.GetKeyUp("r");
if (down)
{
StartCoroutine(LandscapeFast());
}
if (up)
{
StopCoroutine(LandscapeFast());
}
}
public IEnumerator LandscapeFast()
{
yield return new WaitForSeconds(startWait);
while (true)
{
for (int i = 0; i < landscapeCount; i++)
{
GameObject landscape = landscapes[Random.Range(0, landscapes.Length)];
Vector3 spawnPosition = new Vector3(Random.Range(-spawnValues.x, spawnValues.x), spawnValues.y, spawnValues.z);
Quaternion spawnRotation = Quaternion.identity;
Instantiate(landscape, spawnPosition, spawnRotation);
yield return new WaitForSeconds(spawnRate);
}
yield return new WaitForSeconds(waveWait);
}
}
Answer by jdean300 · Feb 24, 2017 at 04:23 AM
Your stop coroutine call is creating a new coroutine rather than using the previous one. What you need to do is save the return value of the Coroutine call:
private IEnumerator coroutine;
private void Update() {
// to start:
coroutine = LandscapeFast();
StartCoroutine(coroutine);
// to stop:
StopCoroutine(coroutine);
}
That is the most beautiful thing to look at. It stopped. Thanks I owe you!
Thank you! 4 years later and no one else answered this question as well as you. After searching for hours you really saved me. Have a good one!
Answer by vkajudiya · Feb 24, 2017 at 11:22 AM
@WilibertXXIV if IEnumerator not contain any parameter then you can use this method also. or if you are in same Monobehaviour then you can use StopAllCoroutines (); to stop all coroutine of current running Script.
bool down = Input.GetKeyDown("r"); bool up = Input.GetKeyUp("r");
if (down)
{
StartCoroutine("LandscapeFast");
}
if (up)
{
StopCoroutine("LandscapeFast");
}