PointCounter.cs 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEngine.UI;
  5. using System.Linq;
  6. using UnityEngine.Networking;
  7. public class PointCounter : MonoBehaviour
  8. {
  9. public Text total;
  10. public List<Text> players;
  11. private string serverUrl;
  12. public GameObject serverManager;
  13. private float period = 0.0f;
  14. // Start is called before the first frame update
  15. void Start()
  16. {
  17. serverUrl = "https://smarthubs.media.tuwien.ac.at/api/get_all_player_points/";
  18. }
  19. // Update is called once per frame
  20. void Update()
  21. {
  22. if (period > 4.0f)
  23. {
  24. //Do Stuff
  25. string currentGame = serverManager.GetComponent<CurrentGameConnect>().GetGameNumber();
  26. Debug.Log(currentGame);
  27. string url = serverUrl + currentGame.ToString();
  28. if(currentGame != "0"){
  29. Debug.Log(url);
  30. StartCoroutine(getValues(url));
  31. }
  32. period = 0;
  33. }
  34. period += UnityEngine.Time.deltaTime;
  35. }
  36. public IEnumerator getValues(string newServerUrl)
  37. {
  38. UnityWebRequest www = UnityWebRequest.Get(newServerUrl);
  39. yield return www.SendWebRequest();
  40. if (www.result != UnityWebRequest.Result.Success)
  41. {
  42. Debug.Log(www.error);
  43. }
  44. else
  45. {
  46. // Show results as text
  47. //Debug.Log(www.downloadHandler.text);
  48. string playerPoints = www.downloadHandler.text;
  49. var result = playerPoints.Split(new[] { ',' })
  50. .Select(s => s.Split(new[] { ':' }))
  51. .ToDictionary(k => k[0].Replace("\"", "").Replace("}", "").Replace("{", "").Trim(), v => v[1].Replace("\"", "").Replace("}", "").Trim());
  52. int i = 0;
  53. int res = 0;
  54. foreach (KeyValuePair<string, string> entry in result)
  55. {
  56. players[i].text = entry.Value;
  57. res += int.Parse(entry.Value);
  58. i++;
  59. Debug.Log("the result is: " + result);
  60. }
  61. total.text = res.ToString();
  62. }
  63. }
  64. }