文章说明
本文记录如何在项目开始时加载远程服务器zip包(包中包含Aot程序集和热更程序集)并解压到对应平台的可持久化路径中(Application.persistentDataPath),并在解压后加载Aot程序集及热更程序集,最后执行项目主流程
项目启动
在unity中创建以下文件夹及文件:

- HotFixScene中增加一个空物体GameEntrance,并挂载脚本【GameEntrance】

using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
public class GameEntrance : MonoBehaviour
{
void Awake()
{
string url = "https://xxx.xxx.com/HotFix.zip";
//检查dll版本,并下载新的dll
DllVersionCheck versionCheck = new DllVersionCheck();
versionCheck.OnDownloadComplete += OnDownloadComplete;
StartCoroutine(versionCheck.DownloadAndExtractZip(url));
}
//extractPath:解压后的文件夹路径
private void OnDownloadComplete(string extractPath)
{
//开始加载新的Dll,进行热更新
Debug.Log($"开始加载Dll,进行热更新:extractPath:{
extractPath}");
DllLoad dllLoad = new DllLoad();
dllLoad.StartDllLoad(extractPath);
}
}
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using UnityEngine;
using UnityEngine.Networking;
/// <summary>
/// Dll版本检查脚本
/// </summary>
public class DllVersionCheck
{
//extractPath:解压后的文件夹路径
public delegate void DownloadCompleteHandler(string extractPath);
public event DownloadCompleteHandler OnDownloadComplete;
public IEnumerator DownloadAndExtractZip(string url)
{
// 下载 ZIP 文件
using (UnityWebRequest request = UnityWebRequest.Get(url))
{
yield return request.SendWebRequest();
if (request.result != UnityWebRequest.Result.Success)
{
Debug.LogError("Error downloading zip file: " + request.error);
yield break;
}
// 保存文件到 persistentDataPath
string zipFilePath = Path.Combine(Application.persistentDataPath, "HotFix.zip");
zipFilePath = zipFilePath.Replace('\\', '/'); // 替换反斜杠为斜杠
Debug.Log($"zipFilePath:{
zipFilePath}");
if (File.Exists(zipFilePath))
{
File.Delete(zipFilePath);
}
File.WriteAllBytes(zipFilePath, request.downloadHandler

190

被折叠的 条评论
为什么被折叠?



