Interestingly enough, if you call stopcoroutine(“test”) from within test, it wont stop that instance of test, but it will stop any other instances of that coroutine.
To see what I am talking about, throw this script onto an empty gameobject and see what happens.
using UnityEngine;
using System.Collections;
public class NewBehaviourScript : MonoBehaviour {
public int number_to_print=1;
void Start () {
StartCoroutine("test");
StartCoroutine("wait_then_test");
}
IEnumerator test(){
StopCoroutine("test");
int number_to_print_in_test=number_to_print;
while(true){
Debug.Log (number_to_print_in_test);
yield return 0;
}
}
IEnumerator wait_then_test(){
yield return new WaitForSeconds(5);
Debug.Log ("created 2nd instance of test");
number_to_print++;
StartCoroutine("test");
}
}
You can see that the first instance stops when the second instance starts. If you comment out the stopcoroutine(“test”), both instances will actually run at the same time.
As a final note, if you call stopallcoroutines() inside of a coroutine, it WILL stop that instance. Try changing stopcoroutine(“test”) to stopallcoroutines() and see what happens.
p.s.
Also, I know the code in your question is just an example, but you forgot to declare the variable “i” before you used it. If that is in any real scripts, it could be causeing some problems.
EDIT: my code is in c#, which is what I use primarily. there may be slight differences in the little quirks of coroutines in unityscript vs c#, but the c# script I posted should work exactly as I said, and yeild break will work in unity script. I saw you were using unityscript, so sorry my answer in in c#
NB the exact syntax for Unity Script is: break; without the yield;
As to why StopCoroutine doesn’t work within a coroutine, I can only guess. It probably
has something to do with the fact that coroutines aren’t like normal functions you call (read this article for more info).
If I had to guess, it would be because StopCoroutine is a MonoBehavior function, and when the compiler creates its dummy class for our coroutine, the MonoBehaviour referenced by StopCoroutine and StartCoroutine in the example aren’t the same.
NB the exact syntax for Unity Script is:
– Will748break;without the yield;