Get www to a string varibale

Hi.

I have a PHP function which returns XML data. I am using C# Unity to retrieve the data to a string variable. I have done this.

In class Requestwww I have

public static text;
public IEnumerator WaitForRequest(WWW www)
    {
       yield return www;
        // check for errors
        if (www.error == null)
        {   //Here I store result in a global variable
            text=www.text;
            Debug.Log("WWW Ok!: " + text);
        }
        else
        {
            Debug.Log("WWW Error: " + www.error);
        }
        
     
    }
    
    public  IEnumerator getxml(string url )
   {
       
        WWW www = new WWW(url);
        if (www == null)
        {
            Debug.Log("www is null");
        }
        else {
            Debug.Log("www is not null");
        }
      
        yield return StartCoroutine(WaitForRequest(www));
        Debug.Log("xmltext here" + text);

    }

And in another class, I call getxml() to start the wwwrequest

Request wwwcall = gameObject.AddComponent<Requestwww>(); 
StartCoroutine(wwwcall.getxml("http://com.example/something.php")
//Here I tried to access the xmltext variable in Requestwww class
Debug.Log("retrived var"+Requestwww.text)
//But text seems tobe null

But it looks like, the variable Requestwww.text is always null when retried from another class. I don’t get it. I called the Coroutine, wait for result, and then update the global varibale, but it seems like the moment I called it from another class, it has not been updated. What should I do? It has taken me a day aching for an answer…

The behavior you are seeing is correct. You need to take a close look at how coroutines function. When you start a coroutine, the routine executes until it hits the first yield, and then returns. So in your code, execution returns to the line 4, second script immediately after it hits line 4 in the first script…and that is before the www has returned with the data. You have some choices for a fix.

  1. You can poll the isDone flag in a loop. Your app will hang until the www is done.

  2. You can put the second script in a coroutine. Then you could do:

    yield return StartCoroutine(wwwcall.getxml(“http://com.example/something.php”);

  3. You can put a check for wwwcall.isDone in a Update() callback, and check it each frame until ‘isDone’ is true.

A bit of reading on coroutines:

http://unitygems.com/coroutines/