Unity3D之http多线程异步资源下载

来源:互联网 发布:淘宝怎么指纹支付 编辑:程序博客网 时间:2024/06/10 14:36

  本文诞生于乐元素面试过程,被面试官问到AssetBundle多线程异步下载时,愣了半天,同样也被深深的鄙视一回(做了3年多U3D 这个都没用过),所以发誓要实现出来填补一下自己的空白,同时分享给大家。说明:本人只在pc和android下测试好使,其他平台未知!

  直接贴代码,都是C# http的API,不懂得自己百科。

  View Code

  下载部分:

[AppleScript] 纯文本查看 复制代码
?
 
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
if(GUI.Button(newRect(0,0,100,30),"test"))
 
{
 
stringrootPath=Application.persistentDataPath;//android上保存到/storage/sdcard0/Android/data/包名(例如:com.example.test)/files
 
for(int i =0;i<str.Length;i++)//str是string型数组,存放部分assetbundle名字
 
{
 
Thread thread =newThread(newParameterizedThreadStart(DownAsset));//ParameterizedThreadStart 多线程传参
 
thread.Start(rootPath+"|"+str[i]);//只能带一个object参数 所以使用字符串拼接
 
}
 
}
 
void DownAsset(System.Objectfile)
 
{
 
string[] fileName =file.ToString().Split('|');
 
HttpHelperhelp=new HttpHelper(fileName[0]);
 
help.AsyDownLoad("http://192.168.0.103/unity/"+fileName[1]+".AssetBundle");//注意在手机上测试 该对Ip地址
 
}



  下载完成后 可以去/storage/sdcard0/Android/data/包名(例如:com.example.test)/files查找对应文件

  加载部分:

[AppleScript] 纯文本查看 复制代码
?
 
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
if(GUI.Button(newRect(0,30,100,30),"load"))
 
{
 
for(int i =0;i<str.Length;i++)
 
{
 
StartCoroutine(LoadAsset(str[i],i));
 
}
 
}
 
IEnumerator LoadAsset(stringname,int i)
 
{
 
WWW w =newWWW("file://"+Application.persistentDataPath+"/"+name+".AssetBundle");
 
yieldreturnw;
 
Instantiate(w.assetBundle.mainAsset,newVector3(i*2,0,0),Quaternion.identity);
 
w.assetBundle.Unload(false);
 
}



  注意事项:

  1、pc测试 需要修改IP地址,本地测试改为127.0.0.1 同时Application.persistentDataPath最好做修改,因为在pc上Application.persistentDataPath:C:\Users\用户名\AppData\LocalLow\DefaultCompany\U3D工程名,可以下载到此文件夹下,但是加载的时候会报错,没什么权限之类的

  2、android上需要stripping level设置为Disabled


原文作者: U_探索 

原文链接:http://www.cnblogs.com/U-tansuo/ ... g_AsyDown_HTTP.html

0 0
原创粉丝点击