Unity技術(shù)博客 - 客戶端斷點(diǎn)續(xù)傳

Unity版本: 5.3

使用語(yǔ)言: C#


寫(xiě)在前面

版本的更新和迭代經(jīng)常遇見(jiàn),Unity中我們可以使用AssetBundle進(jìn)行資源更新,這個(gè)非常方便,客戶端方面下載資源到本地,肯定是要使用斷點(diǎn)續(xù)傳的。

實(shí)現(xiàn)功能:

   1.使用AssetBunlde壓縮場(chǎng)景上傳到服務(wù)器
   2.使用C# Net庫(kù)實(shí)現(xiàn)下載方法(斷點(diǎn)續(xù)傳)
   3.使用Unity的WWW加載使用資源

1.使用AssetBunlde壓縮場(chǎng)景上傳到服務(wù)器

Unity5.X使用AssetBundle打包場(chǎng)景,可以在可視化視圖將要壓縮的資源添加AssetBundle標(biāo)簽,執(zhí)行Build。

為了方便測(cè)試,我將打包好的資源上次到云盤(pán),然后共享了下載鏈接,供我測(cè)試,注意百度云人家也不是傻子,下載鏈接隔天會(huì)失效。

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庫(kù)實(shí)現(xiàn)下載方法(斷點(diǎn)續(xù)傳)

大家記住,計(jì)算機(jī)追求的是效率,關(guān)于費(fèi)時(shí)的操作我們一定要用異步方法或者子線程去處理。

下載資源,肯定是用子線程去處理的,System.Net庫(kù)里面有HttpWebRequset類,提供了訪問(wèn)網(wǎng)址的工具類,我們可以用它下載資源,下載過(guò)程中涉及文件處理的操作,這里用到了流的概念,不懂的先去學(xué)習(xí)流。

using UnityEngine;
using System.Collections;
using System.Threading;
using System.IO;
using System.Net;
using System;

/// <summary>
/// 通過(guò)http下載資源
/// </summary>
public class HttpDownLoad {
    //下載進(jìn)度
    public float progress{get; private set;}
    //涉及子線程要注意,Unity關(guān)閉的時(shí)候子線程不會(huì)關(guān)閉,所以要有一個(gè)標(biāo)識(shí)
    private bool isStop;
    //子線程負(fù)責(zé)下載,否則會(huì)阻塞主線程,Unity界面會(huì)卡主
    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;
        //開(kāi)啟子線程下載,使用匿名方法
        thread = new Thread(delegate() {
            //判斷保存路徑是否存在
            if(!Directory.Exists(savePath))
            {
                Directory.CreateDirectory(savePath);
            }
            //這是要下載的文件名,比如從服務(wù)器下載a.zip到D盤(pán),保存的文件名是test
            string filePath = savePath + "/test";

            //使用流操作文件
            FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Write);
            //獲取文件現(xiàn)在的長(zhǎng)度
            long fileLength = fs.Length;
            //獲取下載文件的總長(zhǎng)度
            long totalLength = GetLength(url);

            //如果沒(méi)下載完
            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)程訪問(wèn)文件流的起始位置
                request.AddRange((int)fileLength);
                Stream  stream = request.GetResponse().GetResponseStream();

                byte[] buffer = new byte[1024];
                //使用流讀取內(nèi)容到buffer中
                //注意方法返回值代表讀取的實(shí)際長(zhǎng)度,并不是buffer有多大,stream就會(huì)讀進(jìn)去多少
                int length = stream.Read(buffer, 0, buffer.Length);
                while(length > 0)
                {
                    //如果Unity客戶端關(guān)閉,停止下載
                    if(isStop) break;
                    //將內(nèi)容再寫(xiě)入本地文件中
                    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();
            }
                
        });
        //開(kāi)啟子線程
        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加載使用資源

注意,測(cè)試的時(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

寫(xiě)在最后

我們一般會(huì)采用多線程下載,這樣速度更快,但是基礎(chǔ)還是要學(xué)的。
#成功的道路沒(méi)有捷徑,代碼這條路更是如此,唯有敲才是王道。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容