使用UnityWebRequest进行下载操作
下载完成后,把文件保存在Application.persistentDataPath目录下面
博主已经真机测试过安卓和Windows系统了,可以放心食用
回调函数
#region//CallBack
public delegate void CallBack();
public delegate void CallBack(T arg);
public delegate void CallBack(T arg1, X arg2);
public delegate void CallBack(T arg1, X arg2, Y arg3);
public delegate void CallBack(T arg1, X arg2, Y arg3, Z arg4);
#endregion
persistentDataPath:常用的做本地缓存目录,它的读写权限都是开放的
///
/// 从服务器下载资源
///
/// 资源地址
/// 文件名字
/// 回调函数
public void LoadAssetsForServer(string uri,string fileName, CallBack action)
{
UnityWebRequest request = UnityWebRequest.Get(uri);
StartCoroutine(LoadAssetsForServer(request, fileName, action));
}
IEnumerator LoadAssetsForServer(UnityWebRequest unityWebRequest, string fileName, CallBack action)
{
yield return unityWebRequest.SendWebRequest();
if (unityWebRequest.isNetworkError)
{
Debug.Log("Download Error:" + unityWebRequest.error);
}
else
{
//下载完成后执行的回调
if (unityWebRequest.isDone)
{
byte[] results = unityWebRequest.downloadHandler.data;
string pathUrl = Application.persistentDataPath+"/File";
//保存文件
GameEntity.local.SaveFile(results, pathUrl, fileName, action);
}
}
}
//补充
//pass:加一个进度条功能
///
/// 从服务器下载资源
///
/// 资源路径
/// 资源保存
/// 保存路径
/// 回调函数
IEnumerator DownloadFileForServer(string url, string resSaveName, string fileSavePath,CallBack callBack)
{
UnityWebRequest request = UnityWebRequest.Get(url);
request.SendWebRequest();
while (true)
{
if (request.isDone)
{
callBack(1);
byte[] results = request.downloadHandler.data;
string pathUrl = Application.persistentDataPath + "/"+ fileSavePath;
GameEntity.local.SaveFile(results, pathUrl, resSaveName);
yield break;
}
else if (request.isNetworkError)
{
callBack(0);
Debug.Log("Download Error:" + request.error);
yield break;
}
else
{
callBack(request.downloadProgress);
}
yield return null;
}
}
///
/// 保存文件到本地
///
///
public void SaveFile(byte[] res,string savePath, string fileUrl, CallBack action)
{
if (!File.Exists(savePath))
{
Directory.CreateDirectory(savePath);
}
string path = savePath + "/" + fileUrl;
FileInfo file = new FileInfo(path);
Stream sw;
sw = file.Create();
sw.Write(res, 0, res.Length);
sw.Close();
sw.Dispose();
action();
}
//使用示例
void Start(){
LoadAssetsForServer("http://192.168.1.1/gamedata.json","gamedata.json",CallAction);
}
void CallAction(){
print("下载完成");
}