I am trying to get and parse JSON file from Google sheets (by url) to my Text object in scene by clicking a button and start method GetAdress(). But my text is going to Update only once (in 1st time clicking).
Is there any solutions? how i could update information in json value?
here is the unity code as well:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
using SimpleJSON;
using System.Text;
using UnityEngine.UI;
using TMPro;
public class ReadGoogleSheet : MonoBehaviour
{
// переменные для тестирования
public TMP_Text outputArea;
List<string> eachrow;
string rowsjson;
string[] lines;
//public GameObject networkerror;
public UnityWebRequest www1 = null;
Coroutine routineLoop;
// Start is called before the first frame update
public void GetAdress()
{
StartCoroutine(ObtainSheetData(www1));
}
IEnumerator ObtainSheetData(UnityWebRequest www)
{
www = UnityWebRequest.Get(";key=AIzaSyCQlPYIzm0X4x6fUR62o-OtFIQvCG15jsc");
yield return www.SendWebRequest();
{
if (www.result == UnityWebRequest.Result.ConnectionError || www.result == UnityWebRequest.Result.ProtocolError || www.timeout > 2)
{
Debug.Log("Error: " + www.error);
Debug.Log("Offline");
}
else
{
string updateText = "";
string json = www.downloadHandler.text;
var o = JSON.Parse(json);
foreach (var item in o["values"])
{
var itemo = JSON.Parse(item.ToString());
eachrow = itemo[0].AsStringList;
foreach (var bro in eachrow)
{
rowsjson += bro + ",";
}
rowsjson += "\n";
updateText = itemo.Value;
}
lines = rowsjson.Split(new char[] { '\n' });
outputArea.text = lines[0] + ": " + lines[1];
if (www.isDone == true)
{
yield return null;
// Things to process in units of frames
// when unityWebRequest has not finished downloading ex) progress
// ...
Debug.Log("Success DownloadData()");
}
}
}
}
}
I am trying to get and parse JSON file from Google sheets (by url) to my Text object in scene by clicking a button and start method GetAdress(). But my text is going to Update only once (in 1st time clicking).
Is there any solutions? how i could update information in json value?
here is the unity code as well:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
using SimpleJSON;
using System.Text;
using UnityEngine.UI;
using TMPro;
public class ReadGoogleSheet : MonoBehaviour
{
// переменные для тестирования
public TMP_Text outputArea;
List<string> eachrow;
string rowsjson;
string[] lines;
//public GameObject networkerror;
public UnityWebRequest www1 = null;
Coroutine routineLoop;
// Start is called before the first frame update
public void GetAdress()
{
StartCoroutine(ObtainSheetData(www1));
}
IEnumerator ObtainSheetData(UnityWebRequest www)
{
www = UnityWebRequest.Get("https://sheets.googleapis/v4/spreadsheets/1XRobihBf7CyH2hLRV7cczki8nLuH2umWM-z63ytavUs/values/Fighters?alt=json&key=AIzaSyCQlPYIzm0X4x6fUR62o-OtFIQvCG15jsc");
yield return www.SendWebRequest();
{
if (www.result == UnityWebRequest.Result.ConnectionError || www.result == UnityWebRequest.Result.ProtocolError || www.timeout > 2)
{
Debug.Log("Error: " + www.error);
Debug.Log("Offline");
}
else
{
string updateText = "";
string json = www.downloadHandler.text;
var o = JSON.Parse(json);
foreach (var item in o["values"])
{
var itemo = JSON.Parse(item.ToString());
eachrow = itemo[0].AsStringList;
foreach (var bro in eachrow)
{
rowsjson += bro + ",";
}
rowsjson += "\n";
updateText = itemo.Value;
}
lines = rowsjson.Split(new char[] { '\n' });
outputArea.text = lines[0] + ": " + lines[1];
if (www.isDone == true)
{
yield return null;
// Things to process in units of frames
// when unityWebRequest has not finished downloading ex) progress
// ...
Debug.Log("Success DownloadData()");
}
}
}
}
}
Share
Improve this question
asked Feb 23 at 13:23
user29764560user29764560
111 bronze badge
6
- So whats the actual issue? – BugFinder Commented Feb 23 at 14:04
- The information from Google sheets updates only once after button is clicked. If i make changes in Google Sheets (just in Unity Runtime) and click button one more time, information wont be updated – user29764560 Commented Feb 23 at 14:21
- what happens when you debug it, when it enters for the second time? – BugFinder Commented Feb 23 at 14:26
- the same value as after 1st click, but if i stop and run scene again in Unity, the information will be updated....in seems that "yield return www.SendWebRequest();" isnt updating in runtime... – user29764560 Commented Feb 23 at 14:35
- well, id argue that your if result clause has flaws, those may not be the only errors returned – BugFinder Commented Feb 23 at 20:29
1 Answer
Reset to default 0If somebody interested in this problem, the answer was in refreshing text variable...and here is how this code should be done:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
using SimpleJSON;
using TMPro;
public class ReadGoogleSheet : MonoBehaviour
{
// Переменные для тестирования
public TMP_Text outputArea;
private List<string> eachrow;
private string[] lines;
private UnityWebRequest www;
private Coroutine requestCoroutine;
// Метод для запуска запроса
public void GetAdress()
{
// Если запрос уже выполняется, отменяем его
if (requestCoroutine != null)
{
StopCoroutine(requestCoroutine);
CancelRequest();
}
// Запускаем новый запрос
requestCoroutine = StartCoroutine(ObtainSheetData());
}
// Корутина для выполнения запроса
IEnumerator ObtainSheetData()
{
// Очищаем предыдущие данные
eachrow = new List<string>();
lines = null;
// Создаем новый запрос
www = UnityWebRequest.Get("https://sheets.googleapis/v4/spreadsheets/1XRobihBf7CyH2hLRV7cczki8nLuH2umWM-z63ytavUs/values/Fighters?alt=json&key=AIzaSyCQlPYIzm0X4x6fUR62o-OtFIQvCG15jsc");
// Устанавливаем таймаут (например, 10 секунд)
www.timeout = 10;
// Отправляем запрос
yield return www.SendWebRequest();
// Обработка результата
if (www.result == UnityWebRequest.Result.ConnectionError || www.result == UnityWebRequest.Result.ProtocolError)
{
Debug.Log("Error: " + www.error);
Debug.Log("Offline");
}
else
{
string json = www.downloadHandler.text;
var o = JSON.Parse(json);
// Очищаем предыдущие данные
string rowsjson = "";
foreach (var item in o["values"])
{
var itemo = JSON.Parse(item.ToString());
eachrow = itemo[0].AsStringList;
foreach (var bro in eachrow)
{
rowsjson += bro + ",";
}
rowsjson += "\n";
}
lines = rowsjson.Split(new char[] { '\n' });
// Обновляем текстовое поле
if (lines.Length > 1)
{
outputArea.text = lines[0] + ": " + lines[1];
}
else
{
outputArea.text = "No data found.";
}
Debug.Log("Success DownloadData()");
Debug.Log(outputArea.text);
}
// Освобождаем ресурсы
CancelRequest();
}
// Метод для отмены запроса и освобождения ресурсов
void CancelRequest()
{
if (www != null)
{
if (!www.isDone)
{
www.Abort();
}
www.Dispose();
www = null;
}
// Сбрасываем ссылку на корутину
requestCoroutine = null;
}
// Очистка при уничтожении объекта
void OnDestroy()
{
CancelRequest();
}
}