Unity UnityWebRequest 下载封装
对unity原生的UnityWebRequest 进行二次封装
public void UnityWebRequestLoad<T>(string path, Action<T> action, string localPath = "",
AudioType audioType = AudioType.MPEG) where T : class
{
StartCoroutine(UnityWebRequestLoadAsync(path, action, localPath, audioType));
}
private IEnumerator UnityWebRequestLoadAsync<T>(string path, Action<T> action, string localPath = "",
AudioType audioType = AudioType.MPEG) where T : class
{
UnityWebRequest req = new UnityWebRequest(path, UnityWebRequest.kHttpVerbGET);
if (typeof(T) == typeof(byte[]))
req.downloadHandler = new DownloadHandlerBuffer();
else if (typeof(T) == typeof(File))
req.downloadHandler = new DownloadHandlerFile(localPath);
else if (typeof(T) == typeof(Texture2D))
req.downloadHandler = new DownloadHandlerTexture();
else if (typeof(T) == typeof(AssetBundle))
req.downloadHandler = new DownloadHandlerAssetBundle(req.url, 0);
else if (typeof(T) == typeof(AudioClip))
req.downloadHandler = new DownloadHandlerAudioClip(req.url, audioType);
else
{
Debug.LogWarning("未知类型:" + typeof(T));
yield break;
}
yield return req.SendWebRequest();
if (req.result == UnityWebRequest.Result.Success)
{
if (typeof(T) == typeof(byte[]))
action?.Invoke(req.downloadHandler.data as T);
else if (typeof(T) == typeof(File))
action?.Invoke(null);
else if (typeof(T) == typeof(Texture2D))
action?.Invoke(DownloadHandlerTexture.GetContent(req) as T);
else if (typeof(T) == typeof(AssetBundle))
action?.Invoke(DownloadHandlerAssetBundle.GetContent(req) as T);
else if (typeof(T) == typeof(AudioClip))
action?.Invoke(DownloadHandlerAudioClip.GetContent(req) as T);
}
else
{
Debug.LogWarning("下载失败:" + req.result + req.error);
}
}