using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using UnityEngine; using UnityEngine.Networking; public class TimeChecker : MonoBehaviour { // 设置的参考时间 public DateTime targetTime; // 最大重试次数 public int maxRetries = 3; // 当前重试次数 private int currentRetry = 0; public Action actionA; public Action actionB; public Action actionC; /// /// 开始检查网络时间并执行相应逻辑 /// public void CheckNetworkTimeAndExecute() { currentRetry = 0; StartCoroutine(TryGetNetworkTime()); } private IEnumerator TryGetNetworkTime() { // 时间服务器列表 string[] timeServers = new string[] { "http://www.ntp.org/", "https://www.baidu.com", "https://www.google.com", "https://time.is/", "https://www.microsoft.com" }; foreach (string server in timeServers) { using (UnityWebRequest www = UnityWebRequest.Get(server)) { www.SetRequestHeader("Cache-Control", "no-cache"); www.timeout = 8; yield return www.SendWebRequest(); if (www.result == UnityWebRequest.Result.Success) { string dateHeader = www.GetResponseHeader("Date"); if (!string.IsNullOrEmpty(dateHeader)) { if (TryParseDate(dateHeader, out DateTime networkTime)) { DateTime localTime = networkTime.ToLocalTime(); Debug.Log($"成功获取网络时间: {localTime:yyyy-MM-dd HH:mm:ss}"); ProcessTimeComparison(localTime); yield break; } else { Debug.LogWarning($"无法解析时间格式: {dateHeader}"); } } else { Debug.LogWarning($"服务器 {server} 未返回Date头信息"); } } else { Debug.LogWarning($"请求 {server} 失败: {www.error}"); } } } // 所有服务器尝试失败,进行重试 currentRetry++; if (currentRetry < maxRetries) { Debug.Log($"重试获取网络时间 ({currentRetry}/{maxRetries})"); yield return new WaitForSecondsRealtime(2f * currentRetry); StartCoroutine(TryGetNetworkTime()); } else { //Debug.LogError("所有尝试都失败,无法获取网络时间"); // 时间获取失败,执行C逻辑 ExecuteLogicC(); } } // 尝试多种格式解析日期 private bool TryParseDate(string dateString, out DateTime dateTime) { string[] formats = { "r", "ddd, dd MMM yyyy HH:mm:ss GMT", "dddd, dd-MMM-yy HH:mm:ss GMT", "yyyy-MM-dd HH:mm:ss", "ddd MMM dd HH:mm:ss yyyy" }; return DateTime.TryParseExact( dateString, formats, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal, out dateTime ); } // 处理时间比较 private void ProcessTimeComparison(DateTime networkTime) { Debug.Log($"设置的目标时间: {targetTime:yyyy-MM-dd HH:mm:ss}"); Debug.Log($"网络时间(本地): {networkTime:yyyy-MM-dd HH:mm:ss}"); if (networkTime <= targetTime) { ExecuteLogicA(); } else { ExecuteLogicB(); } } /// /// 逻辑A:当前时间小于等于设置时间时执行 /// private void ExecuteLogicA() { actionA?.Invoke(); } /// /// 逻辑B:当前时间大于设置时间时执行 /// private void ExecuteLogicB() { actionB?.Invoke(); } /// /// 逻辑C:时间获取失败时执行 /// private void ExecuteLogicC() { actionC?.Invoke(); } // 示例调用 private void OnEnable() { // 设置目标时间示例 targetTime = new DateTime(2025,10,1); CheckNetworkTimeAndExecute(); } }