Search Unity

How to send json data to RESTful API in Unity3D?

Discussion in 'Multiplayer' started by fx3costa, Jun 15, 2015.

  1. fx3costa

    fx3costa

    Joined:
    Feb 23, 2015
    Posts:
    2
    Good afternoon friends!

    I am a programmer and I'm a little time learning about the Unity and the game development universe. I came a doubt that I could not find the answer very well. What is the best architecture or solution to work with a mobile multiplayer game using a restful webservice? It's possible? It is the best way to do something online multiplayer?

    I've been studying a bit WWWForm class and tried to simulate sending data via JSON using JSONObject but without much success. I can not actually send a javascript object.

    An example:

    Code (CSharp):
    1. public void enviar(JSONObject json, Objeto obj)
    2. {
    3.     string url = "http://myurl/unity.php";
    4.  
    5.     WWWForm form = new WWWForm();
    6.  
    7.     form.AddField("var1", "[{\"Nome\":\""+obj.name+"\"}]");
    8.  
    9.     WWW www = new WWW(url, form);
    10.  
    11.     StartCoroutine(WaitForRequest(www));
    12. }
    13.  
    14. IEnumerator WaitForRequest(WWW www)
    15. {
    16.     yield return www;
    17.  
    18.         // check for errors
    19.     if(www.error == null)
    20.     {
    21.         Debug.Log("WWW Ok!: " + www.text);
    22.     } else {
    23.         Debug.Log("WWW Error: "+ www.error);
    24.     }  
    25. }
    and my PHP file I have the following test:

    Code (CSharp):
    1.  
    2. $t = $_POST['var1'];
    3. $novot = json_decode($t);
    4.  
    5. foreach($novot as $novo){
    6. $fp = fopen("bloco1.txt","a");
    7.  
    8. $escreve = fwrite($fp, $novo);
    9.  
    10. fclose($fp);}
    11.  
    All I can back is a stdClass, I can handle, but that to me is something very manual. There is no simple and correct way of working with webservices?
    Thanks in advance!
     
  2. Dustin-Horne

    Dustin-Horne

    Joined:
    Apr 4, 2013
    Posts:
    4,568
    liortal likes this.
  3. fx3costa

    fx3costa

    Joined:
    Feb 23, 2015
    Posts:
    2
    Thanks for the answer! I looked but I was not sure yet. In any case, I think that the best solution can not be even connect via a web service but something like the Photon. I'm still studying it and even to a little lost.
     
  4. jdnichollsc

    jdnichollsc

    Joined:
    Sep 23, 2017
    Posts:
    9
    Last edited: Oct 22, 2017
    RareRooster likes this.
  5. xVergilx

    xVergilx

    Joined:
    Dec 22, 2014
    Posts:
    3,296
    Nice necroposting