Search Unity

Using WWW and waiting for response

Discussion in 'Scripting' started by matrix211v1, Apr 7, 2009.

  1. matrix211v1

    matrix211v1

    Joined:
    Jan 20, 2009
    Posts:
    193
    Hello All:

    I am trying to use the WWW object to get information from a database. This will need to work in the Web Player. I have build a web service and it is working correct. The current issue I have is waiting for the results.

    As an example, this script is attached to a game object called "Database" and the script is called "dbQuery.js":

    Code (csharp):
    1. var urlValue  : String = "http://www.unity3d.com";
    2. var www : WWW;
    3. var result : String;
    4.  
    5. function DatabaseTest (query : String) {
    6.     www = new WWW (urlValue + query);
    7.     yield www;
    8.     result = [url]www.data;[/url]
    9.         Debug.Log("result data return:"+result);
    10. }
    And this code is attached to a game object called "GUILogin" with a scripted called "Login.js":

    Code (csharp):
    1. dbConnect = GameObject.Find("Database").GetComponent(dbQuery);
    2.         dbConnect.DatabaseTest(appendQuery);
    3.         while (!dbConnect.[url]www.isDone[/url])
    4.         {
    5.         }
    6.         Debug.Log("Returned from call:"+dbConnect.return);
    I am well aware that it will cause an infinite loop, I will put a timer in there. The problem is that the "Returned from call" will be executed first before the "result data return" (which will make the dbConnect.return nothing).

    I am also aware that you cannot "return" a value from a function that had a "yield www" in it because you will get that "Generator" error.

    The other question I have to follow up on this is how the garbage collection works. For example, does once my dbQuery.js object is finished with it's call, it it automatically destroyed?

    Thanks for any and all help!

    [EDIT]

    Currently by changing it to:

    Code (csharp):
    1. dbConnect = GameObject.Find("Database").GetComponent(dbQuery);
    2.         dbConnect.DatabaseTest(appendQuery);
    3.         while (!dbConnect.[url]www.isDone[/url])
    4.         {
    5.         }
    6.                 yield new WaitForSeconds (1);
    7.         Debug.Log("Returned from call:"+dbConnect.return);
    Gets me my results I wanted, but I don't like how I am doing it.

    Any thoughts?
     
  2. MatthewW

    MatthewW

    Joined:
    Nov 30, 2006
    Posts:
    1,356
    Chain your yields, like:

    Code (csharp):
    1.  
    2. dbConnect = GameObject.Find("Database").GetComponent(dbQuery);
    3.  
    4. yield dbConnect.DatabaseTest(appendQuery);
    5.  
    6. Debug.Log("Returned from call:"+dbConnect.return);
     
  3. matrix211v1

    matrix211v1

    Joined:
    Jan 20, 2009
    Posts:
    193
    Awesome! That seemed to work. Is there a default timeout or do I need to create one?