GSSReader.cs 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. using System.IO;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using UnityEngine;
  5. using UnityEngine.Networking;
  6. using UnityEngine.Events;
  7. //you can get the data of Google Spreadsheet
  8. public class GSSReader : MonoBehaviour
  9. {
  10. string SheetID = "14rwapJWhB0ffMC4aEKCudh5bqsq2a9hkPnrphA8v438";
  11. string SheetName = "1148909742";//"0";
  12. public UnityEvent OnLoadEnd;
  13. public bool IsLoading { get; private set; }
  14. public string[][] Datas { get; private set; }
  15. IEnumerator GetFromWeb()
  16. {
  17. IsLoading = true;
  18. var tqx = "tqx=out:csv";
  19. var url = "https://docs.google.com/spreadsheets/d/" + SheetID + "/gviz/tq?" + tqx + "&sheet=" + SheetName;
  20. UnityWebRequest request = UnityWebRequest.Get(url);
  21. yield return request.SendWebRequest();
  22. IsLoading = false;
  23. if (request.result == UnityWebRequest.Result.ConnectionError )
  24. {
  25. Debug.LogError(request.error);
  26. OnLoadEnd.Invoke();
  27. }
  28. else
  29. {
  30. Datas = ConvertCSVtoJaggedArray(request.downloadHandler.text);
  31. OnLoadEnd.Invoke();
  32. }
  33. }
  34. public void Reload() => StartCoroutine(GetFromWeb());
  35. static string[][] ConvertCSVtoJaggedArray(string t)
  36. {
  37. var reader = new StringReader(t);
  38. reader.ReadLine(); //skipping over headers
  39. var rows = new List<string[]>();
  40. while (reader.Peek() >= 0)
  41. {
  42. var line = reader.ReadLine(); // Read one line at a time
  43. var elements = line.Split(','); // Row cells are separated by ",".
  44. for (var i = 0; i < elements.Length; i++)
  45. {
  46. elements[i] = elements[i].TrimStart('"').TrimEnd('"');
  47. }
  48. rows.Add(elements);
  49. }
  50. return rows.ToArray();
  51. }
  52. }