Stopping a Coroutine within same function

Hi, guys, is it possible to stop a coroutine using StopCoroutine within the coroutine, something like :

function Awake(){

function Test(){

also, why doesn’t the above stop the coroutine work ?

To stop a coroutine, you use

 yeild break;

within the coroutine.

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 () {
	IEnumerator test(){
		int number_to_print_in_test=number_to_print;
			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");

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.

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#

You can stop a coroutine by using

yield return break;

in UnityScript, possibly just

yield break;

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.