I have a script which I use to get the time from the internet, but the Coroutine, I use sometimes succed, but sometimes I get an error, and I can’t find out what’s cause it. Maybe you guys can help me.
Here’s the script.
public static WorldTime Instance;
private void Awake()
{
if(Instance == null)
{
Instance = this;
DontDestroyOnLoad(this.gameObject);
}
else
{
Destroy(this.gameObject);
}
}
struct TimeData
{
public string datetime;
}
const string API_URL = "http://worldtimeapi.org/api/ip";
public IEnumerator GetRealDateTimeFromAPIOnStart()
{
UnityWebRequest webRequest = UnityWebRequest.Get(API_URL);
Debug.Log("Getting real datetime...");
TimeReady = false;
yield return webRequest.SendWebRequest();
if (webRequest.isNetworkError)
{
Debug.Log("Encountered Error, trying again");
}
else
{
Debug.Log("Succeed");
TimeData timeData = JsonUtility.FromJson<TimeData>(webRequest.downloadHandler.text);
currentTime = ParseDataTime(timeData.datetime);
TimeNow = currentTime;
TimeReady = true;
Scene scene = SceneManager.GetActiveScene();
if(scene.name == "Menu")
{
StartDiffernce = Time.realtimeSinceStartup;
SceneManager.LoadScene("TheFarm");
}
else if (scene.name == "TheFarm")
{
Time.timeScale = 1;
SceneManager.LoadScene("TheFarm");
}
//text.text = currentDateTime.ToString() + "
" + TimeNow.ToString() + "
" + difference.ToString() + "
" + difference.TotalSeconds.ToString();
}
}
private DateTime currentTime;
public DateTime currentDateTime;
public DateTime TimeNow;
public float StartDiffernce;
public TimeSpan difference;
public bool TimeReady = false;
DateTime ParseDataTime(string datatime)
{
string separate;
separate = datatime.Split(‘T’);
string date = separate[0];
string time = separate[1];
separate = time.Split(‘.’);
time = separate[0];
return DateTime.Parse(string.Format("{0} {1}", date, time));
}
public void GettingTimeStart()
{
StartCoroutine(GetRealDateTimeFromAPIOnStart());
}
}
And sometimes I get this error:
“ArgumentException: JSON parse error: Invalid value.
UnityEngine.JsonUtility.FromJson (System.String json, System.Type type) (at <0b59f3b614a04547a8bf657de1e23f2c>:0)
UnityEngine.JsonUtility.FromJson[T] (System.String json) (at <0b59f3b614a04547a8bf657de1e23f2c>:0)
WorldTime+d__4.MoveNext () (at Assets/WorldTime.cs:63)
UnityEngine.SetupCoroutine.InvokeMoveNext (System.Collections.IEnumerator enumerator, System.IntPtr returnValueAddress) (at <42a5878ce129403083acccf18e43363f>:0)”