Unity版本: 5.3
使用語言: C#
寫在前面
版本的更新和迭代經(jīng)常遇見俱两,Unity中我們可以使用AssetBundle進(jìn)行資源更新徘钥,這個(gè)非常方便屁擅,客戶端方面下載資源到本地拙友,肯定是要使用斷點(diǎn)續(xù)傳的辟癌。
實(shí)現(xiàn)功能:
1.使用AssetBunlde壓縮場景上傳到服務(wù)器
2.使用C# Net庫實(shí)現(xiàn)下載方法(斷點(diǎn)續(xù)傳)
3.使用Unity的WWW加載使用資源
1.使用AssetBunlde壓縮場景上傳到服務(wù)器
Unity5.X使用AssetBundle打包場景氏身,可以在可視化視圖將要壓縮的資源添加AssetBundle標(biāo)簽巍棱,執(zhí)行Build。
為了方便測試蛋欣,我將打包好的資源上次到云盤航徙,然后共享了下載鏈接,供我測試,注意百度云人家也不是傻子陷虎,下載鏈接隔天會失效到踏。
using UnityEngine;
using System.Collections;
using UnityEditor;
public class AssetBundleCreate : MonoBehaviour {
[MenuItem("MS/AssetBundleCreate")]
public static void Build()
{
//將資源打包到StreamingAssets文件夾下
BuildPipeline.BuildAssetBundles(Application.streamingAssetsPath);
}
}
2.使用C#Net庫實(shí)現(xiàn)下載方法(斷點(diǎn)續(xù)傳)
大家記住,計(jì)算機(jī)追求的是效率尚猿,關(guān)于費(fèi)時(shí)的操作我們一定要用異步方法或者子線程去處理窝稿。
下載資源,肯定是用子線程去處理的凿掂,System.Net庫里面有HttpWebRequset類伴榔,提供了訪問網(wǎng)址的工具類,我們可以用它下載資源缠劝,下載過程中涉及文件處理的操作潮梯,這里用到了流的概念,不懂的先去學(xué)習(xí)流惨恭。
using UnityEngine;
using System.Collections;
using System.Threading;
using System.IO;
using System.Net;
using System;
/// <summary>
/// 通過http下載資源
/// </summary>
public class HttpDownLoad {
//下載進(jìn)度
public float progress{get; private set;}
//涉及子線程要注意,Unity關(guān)閉的時(shí)候子線程不會關(guān)閉秉馏,所以要有一個(gè)標(biāo)識
private bool isStop;
//子線程負(fù)責(zé)下載,否則會阻塞主線程脱羡,Unity界面會卡主
private Thread thread;
//表示下載是否完成
public bool isDone{get; private set;}
/// <summary>
/// 下載方法(斷點(diǎn)續(xù)傳)
/// </summary>
/// <param name="url">URL下載地址</param>
/// <param name="savePath">Save path保存路徑</param>
/// <param name="callBack">Call back回調(diào)函數(shù)</param>
public void DownLoad(string url, string savePath, Action callBack)
{
isStop = false;
//開啟子線程下載,使用匿名方法
thread = new Thread(delegate() {
//判斷保存路徑是否存在
if(!Directory.Exists(savePath))
{
Directory.CreateDirectory(savePath);
}
//這是要下載的文件名萝究,比如從服務(wù)器下載a.zip到D盤免都,保存的文件名是test
string filePath = savePath + "/test";
//使用流操作文件
FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Write);
//獲取文件現(xiàn)在的長度
long fileLength = fs.Length;
//獲取下載文件的總長度
long totalLength = GetLength(url);
//如果沒下載完
if(fileLength < totalLength)
{
//斷點(diǎn)續(xù)傳核心,設(shè)置本地文件流的起始位置
fs.Seek(fileLength, SeekOrigin.Begin);
HttpWebRequest request = HttpWebRequest.Create(url) as HttpWebRequest;
//斷點(diǎn)續(xù)傳核心帆竹,設(shè)置遠(yuǎn)程訪問文件流的起始位置
request.AddRange((int)fileLength);
Stream stream = request.GetResponse().GetResponseStream();
byte[] buffer = new byte[1024];
//使用流讀取內(nèi)容到buffer中
//注意方法返回值代表讀取的實(shí)際長度,并不是buffer有多大绕娘,stream就會讀進(jìn)去多少
int length = stream.Read(buffer, 0, buffer.Length);
while(length > 0)
{
//如果Unity客戶端關(guān)閉,停止下載
if(isStop) break;
//將內(nèi)容再寫入本地文件中
fs.Write(buffer, 0, length);
//計(jì)算進(jìn)度
fileLength += length;
progress = (float)fileLength / (float)totalLength;
UnityEngine.Debug.Log(progress);
//類似尾遞歸
length = stream.Read(buffer, 0, buffer.Length);
}
stream.Close();
stream.Dispose();
}
else
{
progress = 1;
}
fs.Close();
fs.Dispose();
//如果下載完畢栽连,執(zhí)行回調(diào)
if(progress == 1)
{
isDone = true;
if(callBack != null) callBack();
}
});
//開啟子線程
thread.IsBackground = true;
thread.Start();
}
/// <summary>
/// 獲取下載文件的大小
/// </summary>
/// <returns>The length.</returns>
/// <param name="url">URL.</param>
long GetLength(string url)
{
HttpWebRequest requet = HttpWebRequest.Create(url) as HttpWebRequest;
requet.Method = "HEAD";
HttpWebResponse response = requet.GetResponse() as HttpWebResponse;
return response.ContentLength;
}
public void Close()
{
isStop = true;
}
}
3.使用Unity的WWW加載使用資源
注意险领,測試的時(shí)候下載地址URL,你需要時(shí)時(shí)更新秒紧。
using UnityEngine;
using System.Collections;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
using System;
using System.Net;
using System.IO;
public class Test : MonoBehaviour {
bool isDone;
Slider slider;
Text text;
float progress = 0f;
void Awake()
{
slider = GameObject.Find("Slider").GetComponent<Slider>();
text = GameObject.Find("Text").GetComponent<Text>();
}
HttpDownLoad http;
//隔天之后你需要更新
string url = @"http://nj02all01.baidupcs.com/file/430d880872a1df2c585fdc5d2e1792f7?bkt=p3-00002196e1874bd1f274c739d3812e1223d6&fid=790124421-250528-1052161399548620&time=1453345864&sign=FDTAXGERLBH-DCb740ccc5511e5e8fedcff06b081203-EfEvaTITEN88hc7NwREKd3I5MXs%3D&to=nj2hb&fm=Nan,B,G,ny&sta_dx=14&sta_cs=0&sta_ft=test&sta_ct=0&fm2=Nanjing02,B,G,ny&newver=1&newfm=1&secfm=1&flow_ver=3&pkey=00002196e1874bd1f274c739d3812e1223d6&sl=76480590&expires=8h&rt=sh&r=476311478&mlogid=474664903050570371&vuk=790124421&vbdid=3229687100&fin=test&slt=pm&uta=0&rtype=1&iv=0&isw=0&dp-logid=474664903050570371&dp-callid=0.1.1";
string savePath;
void Start () {
savePath = Application.streamingAssetsPath;
http = new HttpDownLoad();
http.DownLoad(url, savePath, LoadLevel);
}
void OnDisable()
{
print ("OnDisable");
http.Close();
}
void LoadLevel()
{
isDone = true;
}
void Update()
{
slider.value = http.progress;
text.text = "資源加載中" + (slider.value * 100).ToString("0.00") + "%";
if(isDone)
{
isDone = false;
string url = @"file://" + Application.streamingAssetsPath + "/test";
StartCoroutine(LoadScene(url));
}
}
IEnumerator LoadScene(string url)
{
WWW www = new WWW(url);
yield return www;
AssetBundle ab = www.assetBundle;
SceneManager.LoadScene("Demo2_towers");
}
}
工程下載地址
密碼:8c36
寫在最后
我們一般會采用多線程下載绢陌,這樣速度更快,但是基礎(chǔ)還是要學(xué)的熔恢。
#成功的道路沒有捷徑脐湾,代碼這條路更是如此,唯有敲才是王道叙淌。