- Home /
Can't call StopCoroutine function from another script.
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!
When you paste snippets that don't even compile together, it makes it harder for people to help you.
After I got your code samples compiling, it worked fine. Are you sure the method is actually being invoked? Is the game object that hosts the Spawnerwithtime component really named Spawnerwithtime?
Answer by TanselAltinel · Nov 08, 2017 at 08:00 PM
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));
}
}
Your answer
Follow this Question
Related Questions
Loop a function 1 Answer
How can I track if GameObject is null in function? 2 Answers
Item duration doesn't stack 3 Answers
Why is my Unity Crashing when I call a fucntion within coroutine and vice versa? 0 Answers
How to force Coroutine to finish 1 Answer