「Unity」基于UnityWebRequest的HTTP文件断点续传

  • 时间:
  • 浏览:1

yield return headRequest.SendWebRequest();

using System;

using System.Collections;

using System.IO;

using UnityEngine.Networking;

var index = 0;

while (!request.isDone)

{

if (isStop) break;

yield return null;

var buff = request.downloadHandler.data;

if (buff != null)

{

var length = buff.Length - index;

fs.Write(buff, index, length);

index += length;

fileLength += length;

private bool isStop;

var totalLength = long.Parse(headRequest.GetResponseHeader("Content-Length"));

if (fileLength == totalLength)

{

progress = 1f;

}

else

{

progress = fileLength / (float) totalLength;

}

}

}

}

else

{

progress = 1f;

}

var request = UnityWebRequest.Get(url);

request.SetRequestHeader("Range", "bytes=" + fileLength + "-" + totalLength);

request.SendWebRequest();

public void Stop()

{

isStop = true;

}

}

更多unity2018的功能介绍请到paws3d爪爪学院查找。

if (progress >= 1f)

{

isDone = true;

if (callBack != null)

{

callBack();

}

}

}

using (var fs = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Write))

{

var fileLength = fs.Length;

public class HttpDownLoad

{

public float progress { get; private set; }

var dirPath = Path.GetDirectoryName(filePath);

if (!Directory.Exists(dirPath))

{

Directory.CreateDirectory(dirPath);

}

fs.Close();

fs.Dispose();

}

if (fileLength < totalLength)

{

fs.Seek(fileLength, SeekOrigin.Begin);

public IEnumerator Start(string url, string filePath, Action callBack)

{

var headRequest = UnityWebRequest.Head(url);

此处都要手动开启协程

未考虑网络文件变动的大问题,都要搞笑的话可不还可以 自行进行md5比对

若都要分片下载,可不还可以 通过修改Range相关值实现

public bool isDone { get; private set; }