此处需要手动开启协程
未考虑网络文件变动的问题,需要的话可以自行进行md5比对
若需要分片下载,可以通过修改Range相关值实现
using System;
using System.Collections;
using System.IO;
using UnityEngine.Networking;
public class HttpDownLoad
{
public float progress { get; private set; }
public bool isDone { get; private set; }
private bool isStop;
public IEnumerator Start(string url, string filePath, Action callBack)
{
var headRequest = UnityWebRequest.Head(url);
yield return headRequest.SendWebRequest();
var totalLength = long.Parse(headRequest.GetResponseHeader("Content-Length"));
var dirPath = Path.GetDirectoryName(filePath);
if (!Directory.Exists(dirPath))
{
Directory.CreateDirectory(dirPath);
}
using (var fs = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Write))
{
var fileLength = fs.Length;
if (fileLength < totalLength)
{
fs.Seek(fileLength, SeekOrigin.Begin);
var request = UnityWebRequest.Get(url);
request.SetRequestHeader("Range", "bytes=" + fileLength + "-" + totalLength);
request.SendWebRequest();
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;
if (fileLength == totalLength)
{
progress = 1f;
}
else
{
progress = fileLength / (float) totalLength;
}
}
}
}
else
{
progress = 1f;
}
fs.Close();
fs.Dispose();
}
if (progress >= 1f)
{
isDone = true;
if (callBack != null)
{
callBack();
}
}
}
public void Stop()
{
isStop = true;
}
}
更多unity2018的功能介绍请到paws3d爪爪学院查找。