UnityWebRequest基础使用之下载文本、图片、AB包

准备

UnityWebRequest
downloadHandler是一个下载助手,下载的资源可以通过它直接获取
UnityWebRequest继承IDisposable接口
注意:访问的服务器要有下载权限 才能下载

下载文本

IEnumerator LoadText(string url)
{
    using (UnityWebRequest req = UnityWebRequest.Get(url))
    {
        yield return req.SendWebRequest();//发出get请求
        if (req.error == null)
        {
            Debug.Log(req.downloadHandler.text);
            Debug.Log(req.downloadHandler.data.Length);
        }
        else
        {
            Debug.Log("下载出错" + req.responseCode + "," + req.error);
        }
    }
}

下载图片

IEnumerator LoadTexture(string url)
{
    using (UnityWebRequest req = UnityWebRequestTexture.GetTexture(url))
    {
        yield return req.SendWebRequest();
        if (req.error == null)
        {
            Debug.Log((req.downloadHandler as DownloadHandlerTexture).texture.width);
            Debug.Log(DownloadHandlerTexture.GetContent(req).height);
        }
        else
        {
            Debug.Log("下载出错" + req.responseCode + "," + req.error);
        }
    }
}

下载AB包

IEnumerator LoadAB(string url)
{
    using (UnityWebRequest req = UnityWebRequestAssetBundle.GetAssetBundle(url))
    {
        yield return req.SendWebRequest();
        if (req.error == null)
        {
            Debug.Log((req.downloadHandler as DownloadHandlerAssetBundle).assetBundle.name);
            Debug.Log(DownloadHandlerAssetBundle.GetContent(req).name);
        }
        else
        {
            Debug.Log("下载出错" + req.responseCode + "," + req.error);
        }
    }
}

你可能感兴趣的:(Unity经验,前端,开发语言)