coroutine inside a class

Is it possible to call a coroutine inside a class?

This fails, but never triggers an error message, nor a compile error. Removing the yields, it works.

I guess this is the same as a yield in a static function, which cannot work. I don’t understand why, but I can accept it. At the very least it would be good for the editor to trigger an error message.

//attached to a GUITexture
function OnMouseDown () {
	
	var xyz = new DoThis(Time.time);
	yield xyz.ReturnThis();

}

//the class
class DoThis{
	private var xy : int;
	
	function DoThis(xy){
		this.xy = xy * 4;
	}
	
	function ReturnThis() {
		yield WaitForSeconds (.1);
		Debug.Log(xy);
		
	}
	
}

Classes must derive from MonoBehaviour in order to inherit the functionality required to support Unity’s coroutines, so this custom class with no base class doesn’t qualify.

is this what you mean?
Is there a syntax to specify a base class in js? This below does not compile.

class test : MonoBehaviour {

}

I think it would be something like this:

class Test extends MonoBehvaiour
{
}

aha… that does it…
An interesting tidbit

StartCoroutine (temp.ReturnThis());
//temp.ReturnThis();

Calling the function directly leads to a null reference exception, whereas StartCoroutine doesn’t

That’s interesting… so you can do that even on a class which doesn’t derive from MonoBehaviour?

No, you need the monoBehaviour–thanks for the help on that, I couldn’t for my life find ‘extends’ in the docs.

the bit about Start Coroutine strikes me as odd, since Joachim always told us in JS this was unnecessary. although it’s very likely I missed the “except when…” part.

It’s worth noting, you can’t seem to call another coroutine from a coroutine in a class, at least using the method described. I’m not a CS guy, so I’m bumbling through this, sorry.

Anyway, I can now use

yield StartCoroutine (class coroutine());

So I’m happy :slight_smile: