How to use yield within a class function

Im having an issue trying to implement yield within class functions, what im trying to do, is create classes that will contain the behavior of the player/enemies.

Here’s an example of what i’d like to do:

class Body{
private var isStunned:boolean;

function Body(){
<constructor data>

function getStunned(stunTime:int)
yield WaitForSeconds(stunTime);


I’ve checked around looking for other questions, and what they seem to suggest is to call these functions from within a MonoBehavior script, but that doesn’t let me achieve what I want to be able to do. Basically, i’m trying to make a base class that has basic functions that every enemy/player will have and then create aditional classes that extend from it for each.

class imAnEnemy{
private var myBody:body;

function imAnEnemy()
{myBody=new body()}

function isActive()
{<call other functions from body, which may include yield>}


From the example code above, i’d call the isActive() function in the Update Method, but sadly I havent found a way to make this work, is there any elegant alternatives to what I want to do? I know I could just brute-force everything into a MonoBehavior script, but to me that would seem to add too much redundancy.

You have to start them as coroutines - normally Unity does that if you call it from within a MonoBehaviour. If you want a utility class then you are going to need a utility MonoBehaviour script to run the coroutines on. In other words you need a script that’s purpose in life it to execute your coroutines from your library.

It could be as simple as:


    static var instance : CoroutineSupport = this;

    function RunCoroutine(coroutine : IEnumerator)
          return StartCoroutine(coroutine);

Then to start a yielding library routine you would use:


I searched some more and found a solution for my issue. In case its of use to anyone else, here’s the example code of what I found on the Unity forums:

// Coroutiner.js
// this class is just used to run coroutines and needs 
// no further functionality
class Coroutiner extends MonoBehaviour

// Test.js
// a class inheriting from System.Object, using 
// coroutines:

class Test extends System.Object
public static var coroutineRunner : Coroutiner = null;
function Test()
        if (coroutineRunner == null)
            var go = new GameObject("Coroutiner");
            coroutineRunner = go.AddComponent(Coroutiner);      
function Go()
function MyCoroutine()
        Debug.Log("it worked!");