使用UnityWebRequest进行下载操作
下载完成后,把文件保存在Application.persistentDataPath目录下面
persistentDataPath:常用的做本地缓存目录,它的读写权限都是开放的
/// <summary>
/// 从服务器下载资源
/// </summary>
/// <param name="uri">资源地址</param>
/// <param name="fileName">文件名字</param>
/// <param name="action">回调函数</param>
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);
}
}
}
/// <summary>
/// 保存文件到本地
/// </summary>
/// <returns></returns>
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();
}
|