35 lines
1.1 KiB
C#
Raw Normal View History

2025-06-07 17:43:34 +08:00
using System.Collections;
using System.Collections.Generic;
using Cysharp.Threading.Tasks;
using LitJson;
using UnityEngine;
using UnityEngine.Networking;
public class Downloader
{
public static async UniTask<T> DownloadJSONAsync<T>(string url) where T:class
{
using (UnityWebRequest webRequest = UnityWebRequest.Get(url))
{
// 发送请求并等待响应
await webRequest.SendWebRequest().ToUniTask();
if (webRequest.result == UnityWebRequest.Result.ConnectionError || webRequest.result == UnityWebRequest.Result.ProtocolError)
{
Debug.LogError("Error: " + webRequest.error);
return default(T);
}
if (string.IsNullOrEmpty(webRequest.downloadHandler.text))
return default(T);
Debug.Log($"## 下载到json {webRequest.downloadHandler.text}");
// 返回下载的 JSON 字符串
return JsonMapper.ToObject<T>(webRequest.downloadHandler.text);
//return webRequest.downloadHandler.text;
}
}
}