Advertisement
Guest User

UnityScoreApi.cs

a guest
Mar 22nd, 2018
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.82 KB | None | 0 0
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using SimpleJson;
  5. using UnityEngine.Networking;
  6.  
  7. [System.Serializable]
  8. public class UserData
  9. {
  10.     public string user;
  11.     public int score;
  12. }
  13.  
  14. public class Test_API : MonoBehaviour {
  15.  
  16.     void Update()
  17.     {
  18.         if (Input.GetKeyUp(KeyCode.Space))
  19.         {
  20.             TaskOnClick("JohnDoe", 1337);
  21.         }
  22.     }
  23.  
  24.     // POST DATA
  25.  
  26.     IEnumerator WaitForWWW(WWW www)
  27.     {
  28.         yield return www;
  29.  
  30.  
  31.         string txt = "";
  32.         if (string.IsNullOrEmpty(www.error))
  33.             txt = www.text;  //text of success
  34.         else
  35.             txt = www.error;  //error
  36.  
  37.         Debug.Log(txt);
  38.     }
  39.     void TaskOnClick(string user, int score)
  40.     {
  41.         StartCoroutine(PostRequest("http://myAwesomeScore/scoreboard/?format=json", user, score));
  42.     }
  43.  
  44.     IEnumerator PostRequest(string url, string user, int score)
  45.     {
  46.         UserData user = new UserData();
  47.         user.user = user;
  48.         user.score = score;
  49.         string bodyJsonString = JsonUtility.ToJson(user);
  50.         Debug.Log("Data is: \n" + bodyJsonString);
  51.         var request = new UnityWebRequest(url, "POST");
  52.         byte[] bodyRaw = System.Text.Encoding.UTF8.GetBytes(bodyJsonString);
  53.         request.uploadHandler = (UploadHandler)new UploadHandlerRaw(bodyRaw);
  54.         request.downloadHandler = (DownloadHandler)new DownloadHandlerBuffer();
  55.         request.SetRequestHeader("Content-Type", "application/json");
  56.         request.SetRequestHeader("Accept", "application/json");
  57.         yield return request.SendWebRequest();
  58.  
  59.         Debug.Log("Response: " + request.downloadHandler.text);
  60.     }
  61.  
  62.  
  63.     void onRequestFinished(HTTPRequest req, HTTPResponse resp)
  64.     {
  65.         Debug.Log("Request Finished! Text received: " + resp.DataAsText);
  66.     }
  67. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement