Unity version 2022.3.7f1, Windows 10,
Hello, we are having trouble getting Date and Time from internet. A warning messages came up “Non-Secure network connections disabled in Player Settings”.
Should we set it to “Always allowed” < Allow downloads over HTTP* < Player < under Project Settings, with a Warning message (Plain text HTTP connections are not secure and can make your application vulnerable to attacks.).
What is your thought on this? Do most online game Dev set this to “Always allowed”? What if we use www. instead of http? Interesting enough it does work by using <www.worldtimeapi.org/api/ip> Are there any downside?
Script for API see below.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using System.Text.RegularExpressions;
using UnityEngine.Networking;
public class LearnToGetRealDateAndTimeAPIUseTheUnityDudeMethod : MonoBehaviour
{
/* Learn form Stop Time Exploits With Internet-synced Clock | Unity Beginner Tutorial
* by The Unity Dude, 2023SEP26, <https://youtu.be/OJhFlWRMGJg?si=FwVNc8hGzkZ3OJpG>
*
*/
DateTime LocalDateTime, UtcDateTime;
public bool TimeFromServerIsLoaded = false;
struct ServerDateTime
{
public string datetime;// These name need to be exactly the same as seen on the server.
public string utc_datetime;// These name need to be exactly the same as seen on the server.
}// This struct is for extracting data from JSON.
//We may need this script in our entire project that's why we turned it into a Singleton.
#region Singleton class. "This mean only 1 time manager script in the whole game" said Unity Dude.
public static LearnToGetRealDateAndTimeAPIUseTheUnityDudeMethod instance;
private void Awake()
{
if (instance == null)
{
DontDestroyOnLoad(this.gameObject);
instance = this;
}
else
{
Destroy(this.gameObject);
}
}
#endregion
void Start()
{
StartCoroutine(GetDateTimeFromServer());
}
public DateTime getSystemDateTime() // return value will be DateTime
{
return DateTime.Now;
}
public DateTime getSystemDateTimeUTC()
{
return DateTime.UtcNow;
}
public DateTime getServerDateTime()
{
return LocalDateTime.AddSeconds(Time.realtimeSinceStartup);
}
public DateTime getServerDateTimeUTC()
{
return UtcDateTime.AddSeconds(Time.realtimeSinceStartup);
}
IEnumerator GetDateTimeFromServer()
{
Debug.Log("Inside IEnumerator, Getting real date and time from internet.");
UnityWebRequest webRequest = UnityWebRequest.Get("http://worldtimeapi.org/api/ip"); // send the request.
Debug.Log("Before yield return, webRequest = " + webRequest.result.ToString()); //webRequest = InProgress; as seen in Console.
yield return webRequest.SendWebRequest(); // wait for respond.
//The above yield return webRequest.SendWebRequest(); somehow stop anything below
Debug.Log("after yield return, webRequest = " + webRequest.result.ToString());
if (webRequest.result == UnityWebRequest.Result.Success)
{
Debug.Log("inside if statement.");
ServerDateTime serverDateTime = JsonUtility.FromJson<ServerDateTime>(webRequest.downloadHandler.text);
//Next we are going to translate the format from internet to Unity.
LocalDateTime = parseToDateTime(serverDateTime.datetime);
UtcDateTime = parseToDateTime(serverDateTime.utc_datetime);
Debug.Log("Local: " + LocalDateTime.ToString()); // Not displaying anything, since webRequest.result is not successful
Debug.Log("UTC: " + UtcDateTime.ToString());
TimeFromServerIsLoaded = true;
}
else
{
Debug.Log("Failed to load datetime from server. " + webRequest.result.ToString());
}
}
DateTime parseToDateTime(string dateTime)
{
string date = Regex.Match(dateTime, @"^\d{4}-\d{2}-\d{2}").Value;
string time = Regex.Match(dateTime, @"\d{2}:\d{2}:\d{2}").Value;
return DateTime.Parse(string.Format("{0}{1}", date, time));
}
}
Script for UI, displaying date and time see below.
//using System.Collections;
//using System.Collections.Generic;
using UnityEngine;
//using UnityEngine.UI;
using TMPro;
public class LearnToGetRealDateAndTimeUIUsingTheUnityDudeMethod : MonoBehaviour
{
/* Learn form Stop Time Exploits With Internet-synced Clock | Unity Beginner Tutorial
* by The Unity Dude, 2023SEP26, <https://youtu.be/OJhFlWRMGJg?si=FwVNc8hGzkZ3OJpG>
*
*/
public TMP_Text SystemDateTime_text, ServerDateTime_text;
void Update()
{
SystemDateTime_text.text = "Local: " + LearnToGetRealDateAndTimeAPIUseTheUnityDudeMethod.instance.
getSystemDateTime().ToString("yyyyMMMdd HH:mm:ss") + "\nUTC : " + LearnToGetRealDateAndTimeAPIUseTheUnityDudeMethod.instance.
getSystemDateTimeUTC().ToString("yyyyMMMdd HH:mm:ss");
if (LearnToGetRealDateAndTimeAPIUseTheUnityDudeMethod.instance.TimeFromServerIsLoaded)
{
ServerDateTime_text.text = "Server: " + LearnToGetRealDateAndTimeAPIUseTheUnityDudeMethod.instance.
getServerDateTime().ToString("yyyyMMMdd HH:mm:ss") + "\nUTC : " + LearnToGetRealDateAndTimeAPIUseTheUnityDudeMethod.instance.
getServerDateTimeUTC().ToString("yyyyMMMdd HH:mm:ss"); // \n = Environment.NewLine Property
}
else
{
ServerDateTime_text.text = "Server is Not availabe.";
}
}
}