Daniel Daniel - 11 days ago 7
C# Question

yield and WWWForm error

I have been trying to convert the code at (the 2nd sample on the page): http://unity3d.com/support/documentation/ScriptReference/WWWForm.html

..to C# in Unity3D:

void Start ()
{
string dataUrl = "http://www.my-site.com/game/test.php";
string playName = "Player 1";
int score = -1;

// Create a form object for sending high score data to the server
var form = new WWWForm();
// Assuming the perl script manages high scores for different games
form.AddField( "game", "MyGameName" );
// The name of the player submitting the scores
form.AddField( "playerName", playName );
// The score
form.AddField( "score", score );

// Create a download object
WWW downloadW = new WWW( dataUrl, form );

// Wait until the download is done
yield return downloadW;


if(downloadW.error == null) {
print( "Error downloading: " + downloadW.error );
return false;
} else {
// show the highscores
Debug.Log(downloadW.text);
}
}


I get the following error:


error CS1624: The body of
rr2game.Start()' cannot be an iterator block because
void' is not an iterator interface type


After doing some reading I have tried changing void Start() to IEnumerator Start()
..but it says IEnumerator is is not declared..?

If I comment out the yield command the errors go away, but of course the data doesn't load.

Please can someone help?
Thank you.

Answer

yield can not be used in the Start() function, it needs to be called within its own thread, instead try this:

void Start()
{
    StartCoroutine(SaveScore());
}

IEnumerator SaveScore() 
{   
    string dataUrl = "http://www.my-site.com/game/test.php";
    string playName = "Player 1";
    int score = -1;

    // Create a form object for sending high score data to the server
    var form = new WWWForm();
    // Assuming the perl script manages high scores for different games
    form.AddField( "game", "MyGameName" );
     // The name of the player submitting the scores
    form.AddField( "playerName", playName );
     // The score
    form.AddField( "score", score );

    // Create a download object
    WWW downloadW = new WWW( dataUrl, form );

    // Wait until the download is done
    yield return downloadW;


    if(!string.IsNullOrEmpty(downloadW.error)) {
        print( "Error downloading: " + downloadW.error );
    } else {
        // show the highscores
        Debug.Log(downloadW.text);
    }
}