using System; using System.Collections; using System.IO; using UnityEngine; using UnityEngine.Networking; namespace AOT.Patch { public sealed class VersionClient { readonly string _url; readonly bool _allowStreamingFallback; public VersionClient(string url, bool allowStreamingFallback) { _url = url; _allowStreamingFallback = allowStreamingFallback; } public IEnumerator Fetch(Action onDone) { string error = null; VersionInfo info = null; if (!string.IsNullOrEmpty(_url)) { using (var req = UnityWebRequest.Get(_url)) { req.timeout = 15; yield return req.SendWebRequest(); #if UNITY_2020_2_OR_NEWER bool failed = req.result != UnityWebRequest.Result.Success; #else bool failed = req.isNetworkError || req.isHttpError; #endif if (!failed) { info = VersionInfo.FromJson(req.downloadHandler.text); if (info == null) error = "version.json parse failed"; } else { error = req.error; } } } if (info == null && _allowStreamingFallback) { var localPath = Path.Combine(Application.streamingAssetsPath, "cdn", "version.json"); yield return ReadLocalText(localPath, text => { if (!string.IsNullOrEmpty(text)) { info = VersionInfo.FromJson(text); if (info != null) error = null; } }); } onDone?.Invoke(info, error); } static IEnumerator ReadLocalText(string path, Action onDone) { #if UNITY_ANDROID && !UNITY_EDITOR using (var req = UnityWebRequest.Get(path)) { yield return req.SendWebRequest(); #if UNITY_2020_2_OR_NEWER bool failed = req.result != UnityWebRequest.Result.Success; #else bool failed = req.isNetworkError || req.isHttpError; #endif onDone?.Invoke(failed ? null : req.downloadHandler.text); } #else if (File.Exists(path)) onDone?.Invoke(File.ReadAllText(path)); else onDone?.Invoke(null); yield break; #endif } } }