下载Nginx并解压(如果有其他方便易用的web服务器都可以)
因为大部分开发都会放在Windows下,为了方便开发,这里下载Windows版。
启动nginx
启动nginx有两种方式:
- 双击启动
- cmd 命令启动
直接双击 nginx.exe
,双击后一个黑色的弹窗一闪而过 。 这样就是启动成功了。
用 管理员权限 打开cmd,切换到nginx解压目录下,输入命令 start nginx.exe
或者 nginx.exe
,回车后会出现一个黑色的弹窗一闪而过。如果没有设置过防火墙,会有如下弹窗,通过即可。
访问 http://localhost/
编辑 Nginx 配置文件:conf/nginx.conf
在配置文件中添加以下内容,以指定下载文件的路径:
server {
location /download/ {
root C:/path/to/your/ab/files; # 替换为你的 AB 包所在目录
sendfile on;
autoindex on;
autoindex_exact_size on;
autoindex_localtime on;
charset utf-8;
index index.html index.htm;
}
}
然后通过 http://localhost/download/xxx.ab
下载 Unity 制作的预制体的 AB 包。
可以放一个测试文件试一下是否可以下载
服务器下载跑通之后就可以通过UnityWebRequest来下载获取服务器上资源文件包
private IEnumerator Loading(Action callback)
{
//获取服务器资源版本号
UnityWebRequest request = UnityWebRequest.Get(ASSET_BUNDLE_URL + "version.txt");
yield return request.SendWebRequest();
if (request.result != UnityWebRequest.Result.Success)
{
SHLog.Error("Error downloading file: " + request.error);
yield break;
}
List<string> abNeedUpdate = GetAssetBundleNeedUpdated(request.downloadHandler.text, out string version);
//获取本地资源版本号
string localVersion = PlayerPrefs.GetString("version");
//版本一致,不需要更新
if (localVersion != ""
&& version == localVersion
&& abNeedUpdate.Count == 0)
{
yield break;
}
PlayerPrefs.SetString("version", version);
//下载AssetInfo
yield return DownloadFile(ASSET_BUNDLE_URL + "AssetInfo", Application.persistentDataPath + "/AssetBundle/AssetInfo");
//下载资源
for (int i = 0; i < abNeedUpdate.Count; i++)
{
yield return DownloadFile($"{ASSET_BUNDLE_URL}{abNeedUpdate[i]}", $"{Application.persistentDataPath}/AssetBundle/{abNeedUpdate[i]}");
//下载manifest
yield return DownloadFile($"{ASSET_BUNDLE_URL}{abNeedUpdate[i]}.manifest", $"{Application.persistentDataPath}/AssetBundle/{abNeedUpdate[i]}.manifest");
//更新下载进度
//LoadingManager.Ins.UpdateProgress((float)i / abNeedUpdate.Count);
}
//下载Lua的Hotfix
yield return DownloadFile(HOTFIX_URL + "HotfixFunc.lua.txt", Application.persistentDataPath + "/Hotfix/HotfixFunc.lua.txt");
yield return DownloadFile(HOTFIX_URL + "LuaDispose.lua.txt", Application.persistentDataPath + "/Hotfix/LuaDispose.lua.txt");
callback?.Invoke();
}
如果有需要做断点续传的话可以继承 DownloadHandlerScript
类,并在基类构造函数中传递一个固定大小的缓冲区作为下载的缓冲区。这种方式不会产生新的垃圾回收(GC),内存使用平稳。