Unity UnityWebRequest 下载封装

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);
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值