WWW to UnityWebRequest

Hello guys im stuck with converting WWW to UnityWebRequest.
Im running my game on a localhost server it needs to connect to.

    public void CallRegister()
    {
        StartCoroutine(Register());
    }

    IEnumerator Register()
    {
        WWWForm form = new WWWForm();
        form.AddField("name", nameField.text);
        form.AddField("password", passwordField.text);
        WWW www = new WWW("http://localhost/sqlconnect/register.php", form);
        yield return www;
        if(www.text == "0")
        {
            Debug.Log("User created successfully");
            SceneManager.LoadScene(0);
        }
        else
        {
            Debug.Log("User creating failed. Error # " + www.text);
        }
    }

Thanks for looking in to it.

Start with the example code in the UnityWebRequest docs. There are several different ones, the one you probably want is the GET one, but I don’t know your service.

EDIT: Aurimas is probably right below… you probably want POST.

Based on your code, you want to look at documentation for UnityWebRequest.Post.

2 Likes

UnityWebRequest is very similar to WWW. Essentially, your code would look like this:
If you’re getting a response from the server, you’ll need to use www.downloadHandler.data which is an array of bytes and encode them into whatever they’re suppose to be.

IEnumerator Register()
    {
        WWWForm form = new WWWForm();
        form.AddField("name", nameField.text);
        form.AddField("password", passwordField.text);

        //Create the request using a static method instead of a constructor
        UnityWebRequest www = UnityWebRequest.Post("http://localhost/sqlconnect/register.php", form);

        //Start the request with a method instead of the object itself
        yield return www.SendWebRequest();

       
         byte[] responseBytes = www.downloadHandler.data;
         string responsefromserver = Encoding.UTF8.GetString(responseBytes);
    }
1 Like

This does the same as:

string responseFromServer = www.downloadHandler.text;

3 Likes

Hello guys quick update i tried these options but it looks like its not working yet. also havent been able to find a solution myself.

Thanks in advance
Appreciate the help

Is your URL even complete? If you actually host the game, you’ve most likely specified a port for the server. That port one should appear in the address.

Im running a localhost server over MAMP PRO. so localhost should work because it previously worked with WWW

If it previously worked with WWW it should work with UnityWebRequest as well.
Because the WWW API is creating a UnityWebRequest for you.

– This is the decompiled code using Rider. –

    public WWW(string url, WWWForm form)
    {
      this._uwr = UnityWebRequest.Post(url, form);
      this._uwr.chunkedTransfer = false;
      this._uwr.SendWebRequest();
    }

now chunkedTransfer should be by default already false. Because it is not supported by most servers.
Unless you’re running some really old version of Unity.

The piece of code below is compatible with Unity 2020.1.17.
If you run this, what do you get in return from your hosted server?
If you don’t get a debug at all, make sure the game object & component the coroutine is running on, stays active at least until it has been finished. An inactive game object a coroutine is running on is stopped.

IEnumerator Register()
{
    // Form stays the same
    var form = new WWWForm();
    form.AddField("name", nameField.text);
    form.AddField("password", passwordField.text);
   
    // You're using Post because you're sending a form with
    // WWW www = new WWW("http://localhost/sqlconnect/register.php", form);
   
    // 'using' will dispose the request once it is done running or encounters an error while running
    using(var postRequest = UnityWebRequest.Post("http://localhost/sqlconnect/register.php", form))
    {
        postRequest.timeout = 30;
        // For a request to run you have to call SendWebRequest();
        // And since it is a AsyncOperation you can yield it.
        yield return postRequest.SendWebRequest();

        // After it has been sent you can fetch the results.
        if (postRequest.result == UnityWebRequest.Result.Success)
        {
            Debug.Log("Successfully posted");
            var serverResponse = postRequest.downloadHandler.text;
            Debug.Log($"Server Responded with\n{serverResponse}");
           
            if(serverResponse.Equals("0", StringComparison.Ordinal))
            {
                Debug.Log("The User is created successfully");
                // Do Stuff
            }
            else
            {
                Debug.Log($"User creating failed. Error # {serverResponse}");
                // Failed to register
            }
        }
        else
        {
            // Response failed as a whole. Look up the details.
            Debug.LogWarning($"We failed to post the request.\nUrl: {postRequest.uri}\nResult: {postRequest.result}\nError: {postRequest.error}\nResponse Code: {postRequest.responseCode}");
        }
    }
}

Thanks for the explanation.

StringComparison.Ordinal - this part gives an error in my code. Its written in C#.

If it is a webgl build then yeah it might be unavailable to compare with ordinal. At least I vaguely remember such issue. You can remove the ordinal part then.

if you test this in the editor it should work though. Unless the Text string given by the server is not equal to “0”

If you reach the point of comparison then you have a comparison / server response problem and not a webrequest problem

I’m still new at this and Im learning c++ and kinda don’t understend c# how woud i change this code

IEnumerator LoadTexture()
    {
        WWW www = new WWW(FinalPath);
        while(!www.isDone)
            yield return null;
        Player.GetComponent<Renderer>().sharedMaterial.mainTexture = www.texture;
    }