Hi, I need to call a coroutine from a static function.

I don’t know too much about coroutines… but I think I need it for loading a file using WWW.

I found this, but I don’t understand how to use it…

Here is my static function:

public static string getFile(string path){

www = new WWW(path);

return www.text;

}

Any helps?

Ok so you can’t do what you want to do quite like that. The WWW will not wait when you call this, so when you call getFile you cannot have the string immediately. A good way of handling this is to use closures (it’s techy, more on Unity Gems).

So I presume you currently do something like this:

  someString = SomeClass.getFile("SomeURL");
  Debug.Log(someString);
  Process(someString);

Because of the delay we need to execute the 2nd and 3rd lines when the data is available, not straight away. To do that we create an Action closure.

  SomeClass.getFile("SomeURL",(someString)=>{
     Debug.Log(someString);
     Process(someString);
  });

So we’ve defined the subsequent statements as a thing we can call when the data is available. Now we need to modify the code from that other thread so that it can deal with all of this! Here’s the code - add it to an new empty GameObject in your scene:

#StaticCoroutine.cs

public class StaticCoroutine : MonoBehaviour{

 static public StaticCoroutine instance; //the instance of our class that will do the work

 

 void Awake(){ //called when an instance awakes in the game

  instance = this; //set our static reference to our newly initialized instance

 }

 IEnumerator Perform(IEnumerator coroutine, Action onComplete = null)
 {
     onComplete = onComplete ?? delegate {};
     yield return StartCoroutine(coroutine);
     onComplete();
 }

 static public void DoCoroutine(IEnumerator coroutine, Action onComplete = null){

  instance.StartCoroutine(instance.Perform(coroutine, onComplete)); //this will launch the coroutine on our instance

 }

}

Now we modify getFile to call that code and pass on your closure:

    public static void getFile(string path, Action<string> onComplete)
    {
           StaticCoroutine.DoCoroutine(DoGetFile(path, onComplete));
    }

    static IEnumerator DoGetFile(string path, Action<string> onComplete)
    {
           var www = new WWW(path);
           yield return www;
           onComplete(www.text);
    }

So to round up - there’s a modified version of the code from that other thread that works the way we need it to. You’ve rewritten getFile to start the coroutine and pass on the functions that you want to execute when the data is available later. Please note that in that function you now pass to getFile you can still access local variables - but do not access foreach or for loop variables unless you use a copy you take of them (it’s a weird glitch).