This repository has been archived on 2025-04-11. You can view files and clone it, but cannot push or open issues or pull requests.
mochapine64backup/MoCha/Assets/Scripts/GetData.cs
2018-04-18 18:15:11 -05:00

126 lines
2.2 KiB
C#

using UnityEngine;
using UnityEngine.Networking;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;
/*
* USAGE
*
* Just put this script into a button that needs
* to execute the HTTP request, and in the text field
* write the exact URL needed for the request.
*
* */
public class GetData : MonoBehaviour
{
Text objectText;
void Start()
{
objectText = GetComponentInParent<Text> ();
}
public void DisplayStuff(string request)
{
StartCoroutine (MakeRequest (request));
}
IEnumerator MakeRequest(string request)
{
using (UnityWebRequest www = UnityWebRequest.Get(request))
{
yield return www.SendWebRequest();
if (www.isNetworkError || www.isHttpError)
{
Debug.Log(www.error);
}
else
{
//this should be saved somewhere else...
List<PlayerInfo> players;
// Show results as text
players = ParseJsonRaw(www.downloadHandler.text);
objectText.text = DisplayInfo (players);
// Or retrieve results as binary data
byte[] results = www.downloadHandler.data;
}
}
}
public List<PlayerInfo> ParseJsonRaw(string json)
{
List<PlayerInfo> players = new List<PlayerInfo>();
string tempjson = "";
bool ignorequotes = false;
bool specialchar = false;
bool insideobject = false;
foreach (char c in json)
{
if (insideobject)
{
tempjson += c;
}
if (c == '\"')
{
if (!specialchar)
{
ignorequotes = !ignorequotes;
}
}
if(specialchar)
{
specialchar = false;
}
if(c == '\\')
{
specialchar = true;
}
if (!ignorequotes)
{
if (c == '{')
{
insideobject = true;
tempjson += c;
}
else if (c == '}')
{
insideobject = false;
players.Add(ParseJson(tempjson));
tempjson = "";
}
}
}
return players;
}
public PlayerInfo ParseJson(string json)
{
return JsonUtility.FromJson<PlayerInfo>(json);
}
public string DisplayInfo(List<PlayerInfo> p)
{
string output = "";
foreach (PlayerInfo pi in p)
{
output += "Player ID: " + pi.user_id + "\t\tUser: " + pi.username + "\n";
}
return output;
}
}