Unity下载问题WWW和UnityWebRequest

时间:2019-10-12 10:28:22

标签: c# unity3d networking

我正在尝试使用URL下载资产捆绑,以下是我正在使用的代码:

WWW www = new WWW(assetsFilepath);

while (!www.isDone)
{
    Debug.Log("Downloading asset: " + www.progress);
    yield return null;
}

yield return www;

if (www.error == null)               
{                    
    Debug.Log("No Error");
    string tempPath = Path.Combine(Application.persistentDataPath, assetsFilename);
    FileStream cache = new FileStream(path, FileMode.Create);
    cache.Write(www.bytes, 0, www.bytes.Length);
    cache.Close();
}                
else
{
    Debug.Log(www.error);
}

Log Output: Downloading asset: 0

我知道WWW请求已过时,因此我尝试了以下操作:

UnityWebRequest www = UnityWebRequestAssetBundle.GetAssetBundle(assetsFilepath);

while (!www.isDone)
{
    Debug.Log("Downloading asset: " + www.downloadProgress);
    yield return null;
}

yield return www.SendWebRequest();
if (www.error == null)
{
    Debug.Log("No Error");
    string tempPath = Path.Combine(Application.persistentDataPath, assetsFilename);
    FileStream cache = new FileStream(path, FileMode.Create);
    cache.Write(www.downloadHandler.data, 0, www.downloadHandler.data.Length);
    cache.Close();
}
else
{
    Debug.Log(www.error);
}

Log Output : Downloading asset: 0

Unity:2018.3.8f

在播放器设置中写入权限:外部SD卡

授予外部读取和写入权限

这是我第一次使用UnityWebRequest,我无法找到每次都得到这个的原因。我错过任何一步了吗?或任何设置?

2 个答案:

答案 0 :(得分:1)

在开始下载之前,您正在等待下载完成。 您的代码应如下所示。

1)创建一个请求:UnityWebRequest www = UnityWebRequestAssetBundle.GetAssetBundle(assetsFilepath);

2)

  • 发送请求并使用以下一行来等待它:yield return www.SendWebRequest();

  • 或如果要跟踪进度,则不发送任何内容。

        www.SendWebRequest();
        while (!www.isDone)
        {
            Debug.Log(www.progress);
            yield return null;
        }
    

3)现在完成,等待下载处理程序完成数据处理:

while(!www.downloadHandler.isDone)
   yield return null;

4)现在,在www.downloadHandler.data上享受下载的数据

答案 1 :(得分:0)

这对我有用...

UnityWebRequest www = UnityWebRequestAssetBundle.GetAssetBundle(assetsFilepath);
www.SendWebRequest();
while (!www.isDone)
{
    Debug.Log("Downloading asset: " + www.downloadProgress);
}
if (www.error == null)
{
    string tempPath = Path.Combine(Application.persistentDataPath, assetsFilename);
    FileStream cache = new FileStream(path, FileMode.Create);
    cache.Write(www.downloadHandler.data, 0, www.downloadHandler.data.Length);
    cache.Close();
}