11-02-实战-YooAsset+HybridCLR完整热更新项目

实战-YooAsset+HybridCLR完整热更新项目

篇章:11-实战篇-完整项目实战
状态:完成
阅读时间:约 40 分钟


一、引言

1.1 本章在系列中的定位

热更新能力是现代手游的必备特性。在 Unity 生态中,资源热更新可以通过 YooAsset 实现,而代码热更新则需要借助 HybridCLR(原 huatuo)这类第三方方案。将两者结合,可以实现完整的代码 + 资源热更新闭环。

本章将深入讲解如何在一个 Unity 项目中同时集成 YooAsset 和 HybridCLR,实现真正的"无感热更新"。

1.2 本章要解决的核心问题

  • 如何设计同步热更代码和资源的整体架构?
  • 如何实现资源差量更新以减少玩家的下载量?
  • HybridCLR + YooAsset 集成时有哪些常见的坑?
  • 如何保证热更新的安全性、稳定性和可回滚性?

1.3 阅读前置要求

  • 熟悉 HybridCLR 的基本概念(AOT + Interpreter 模式)
  • 了解 YooAsset 的热更新流程(参考本书第 09 章)
  • 有 C# 反射和 Assembly 加载的基础知识

1.4 整体架构

Game Client
├── Main (AOT 主工程)
│   ├── GameLauncher.cs        # 启动入口
│   ├── HybridCLRManager.cs    # 热更 DLL 管理器
│   ├── YooAssetManager.cs     # 资源管理器
│   └── VersionManager.cs      # 版本管理器
│
├── Hotfix (热更 DLL)
│   ├── HotfixEntry.cs         # 热更入口
│   ├── UIManager.cs           # UI 管理器
│   ├── SceneManager.cs        # 场景管理器
│   └── GameLogic.cs           # 业务逻辑
│
└── Resources (资源)
    ├── BuiltIn (首包资源)
    ├── Patch (补丁资源)
    └── HotfixDLL (热更 DLL 文件)

二、HybridCLR 环境搭建与配置

2.1 HybridCLR 简介

HybridCLR 是一个基于 Unity IL2CPP 的扩展方案,它实现了完整的 AOT + Interpreter 混合运行模式:

  • AOT 部分:主工程代码(Main DLL)通过 IL2CPP 编译为原生代码
  • Interpreter 部分:热更代码(Hotfix DLL)以 IL 指令形式运行在 HybridCLR 的解释器中

这种架构的优势在于:

特性 传统 Lua 热更 HybridCLR 热更
开发语言 Lua(额外学习成本) C#(与主工程一致)
性能 Lua 调用 C# 有性能损耗 解释器模式,接近原生
调试体验 调试困难 支持 VS 调试热更代码
代码复用 需要跨语言桥接 直接引用主工程代码
生态兼容 Lua 第三方库有限 兼容绝大多数 C# 库

2.2 HybridCLR 的工作原理

理解 HybridCLR 的工作原理对于正确配置和使用至关重要。HybridCLR 在 IL2CPP 的基础上增加了一个 CLI(Common Language Infrastructure)解释器,使得程序集可以在解释模式下运行。

当 Unity 使用 IL2CPP 编译时,AOT 部分的代码会被编译成 C++ 代码,然后进一步编译为原生机器码执行。Hotfix 部分的 C# 代码不会被 IL2CPP 编译,而是以原始的 IL(Intermediate Language)指令形式打包成 DLL 文件。HybridCLR 运行时内置了一个高效的 IL 解释器,专门负责执行这些热更 DLL 中的代码。

这种架构带来的关键特性是:热更代码可以直接引用 AOT 代码中定义的类型和方法,调用性能远高于 Lua 方案,因为不需要跨语言桥接。热更代码之间的方法调用完全在解释器内部完成,性能接近于原生 IL2CPP 代码的 70% 到 90%。

然而,这种架构也带来了一些限制。最大的限制是泛型问题:当热更代码中实例化了一个 AOT 侧没有用过的泛型类型时,IL2CPP 没有生成对应的 C++ 代码,HybridCLR 的解释器也无法自动补全。这就是为什么我们需要进行泛型预留(Generic Reserve),提前告诉编译器哪些泛型类型可能被热更代码使用。

另一个重要的限制是反射行为:某些反射操作(如 MethodInfo.Invoke)在解释模式下的性能较差,不适合频繁调用。在热更代码中应该尽量使用委托或接口来替代反射。

2.3 HybridCLR 安装与配置

// 步骤 1: 安装 HybridCLR 包
// 在 Unity Package Manager 中添加:
// https://github.com/focus-creative-games/hybridclr_unity.git

// 步骤 2: 配置 HybridCLR 面板
// HybridCLR -> Settings
// - 配置 Hot Update Assemblies(热更新程序集列表)
// - 配置 AOT Assemblies(预编译程序集列表)

// 步骤 3: 安装完成后执行
// HybridCLR -> Installer -> Install

HybridCLR 管理器实现

using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using UnityEngine;
using YooAsset;

/// <summary>
/// HybridCLR 热更 DLL 管理器
/// 负责从 YooAsset 加载热更 DLL 并注册到运行时
/// </summary>
public class HybridCLRManager : MonoBehaviour
{
    [Header("热更 DLL 配置")]
    public string hotfixDLLPackage = "DefaultPackage";
    public string hotfixDLLDirectory = "HotfixDLL";

    // 需要加载的热更程序集列表
    private readonly List<string> hotUpdateAssemblies = new List<string>
    {
        "Hotfix.dll",
        "Hotfix.UI.dll",
        "Hotfix.GameLogic.dll"
    };

    // 已加载的程序集
    private readonly Dictionary<string, Assembly> loadedAssemblies = new Dictionary<string, Assembly>();

    // 加载进度
    public float LoadProgress { get; private set; }
    public bool IsLoaded { get; private set; }
    public string LastError { get; private set; }

    public event Action OnHotfixLoadComplete;
    public event Action<string> OnHotfixLoadFailed;

    private ResourcePackage resourcePackage;

    private void Start()
    {
        resourcePackage = YooAssets.GetPackage(hotfixDLLPackage);
    }

    /// <summary>
    /// 加载所有热更 DLL
    /// </summary>
    public IEnumerator LoadHotfixDLLs()
    {
        IsLoaded = false;
        int totalAssemblies = hotUpdateAssemblies.Count;
        int loadedCount = 0;

        foreach (string assemblyName in hotUpdateAssemblies)
        {
            string location = $"{hotfixDLLDirectory}/{assemblyName}";
            Debug.Log($"[HybridCLR] 加载热更程序集: {location}");

            // 通过 YooAsset 加载 DLL 文件
            var handle = resourcePackage.LoadAssetAsync<TextAsset>(location);

            while (!handle.IsDone)
            {
                LoadProgress = (float)loadedCount / totalAssemblies +
                    (handle.Progress / totalAssemblies);
                yield return null;
            }

            if (handle.Status == EOperationStatus.Succeed)
            {
                TextAsset dllAsset = handle.AssetObject as TextAsset;

                if (dllAsset != null && dllAsset.bytes != null)
                {
                    try
                    {
                        // 加载程序集
                        Assembly assembly = Assembly.Load(dllAsset.bytes);
                        loadedAssemblies[assemblyName] = assembly;
                        loadedCount++;

                        Debug.Log($"[HybridCLR] 程序集加载成功: {assemblyName}, " +
                            $"大小: {dllAsset.bytes.Length / 1024f:F1}KB");
                    }
                    catch (Exception ex)
                    {
                        LastError = $"程序集加载异常: {assemblyName}, {ex.Message}";
                        Debug.LogError($"[HybridCLR] {LastError}");
                        OnHotfixLoadFailed?.Invoke(LastError);
                    }
                }
                else
                {
                    LastError = $"DLL 文件为空: {assemblyName}";
                    Debug.LogError($"[HybridCLR] {LastError}");
                }

                handle.Release();
            }
            else
            {
                LastError = $"加载失败: {location}, {handle.Error}";
                Debug.LogError($"[HybridCLR] {LastError}");
                OnHotfixLoadFailed?.Invoke(LastError);
            }
        }

        LoadProgress = 1f;
        IsLoaded = loadedCount == totalAssemblies;

        if (IsLoaded)
        {
            Debug.Log("[HybridCLR] 所有热更程序集加载完成");
            OnHotfixLoadComplete?.Invoke();
        }
    }

    /// <summary>
    /// 获取指定类型的程序集
    /// </summary>
    public Assembly GetAssembly(string name)
    {
        if (loadedAssemblies.TryGetValue(name, out Assembly assembly))
        {
            return assembly;
        }
        return null;
    }

    /// <summary>
    /// 在热更程序集中查找指定类型
    /// </summary>
    public Type FindHotfixType(string fullTypeName)
    {
        foreach (var assembly in loadedAssemblies.Values)
        {
            Type type = assembly.GetType(fullTypeName);
            if (type != null)
            {
                return type;
            }
        }
        return null;
    }

    /// <summary>
    /// 调用热更入口方法
    /// </summary>
    public void InvokeHotfixEntry(string methodName, params object[] args)
    {
        Type entryType = FindHotfixType("Hotfix.HotfixEntry");
        if (entryType != null)
        {
            MethodInfo method = entryType.GetMethod(methodName,
                BindingFlags.Public | BindingFlags.Static);
            if (method != null)
            {
                method.Invoke(null, args);
                Debug.Log($"[HybridCLR] 调用热更入口方法: {methodName}");
            }
            else
            {
                Debug.LogError($"[HybridCLR] 找不到热更入口方法: {methodName}");
            }
        }
        else
        {
            Debug.LogError("[HybridCLR] 找不到 HotfixEntry 类型");
        }
    }
}

2.4 热更 DLL 的构建与版本管理

HybridCLR 的热更 DLL 构建流程与普通 C# 项目不同。热更 DLL 不能依赖于 Unity 的编辑器环境,而是作为一个独立的 .NET Standard 2.0 类库项目进行编译。在实际项目中,热更代码通常组织为一个或多个独立的 Visual Studio 项目或脚本编译管线。

热更 DLL 的构建流程大致如下:首先在 Visual Studio 中创建 .NET Standard 2.0 类库项目,添加对主工程 AOT DLL 的引用;然后编写业务逻辑代码;最后通过 MSBuild 或 Unity 的脚本编译管线生成 DLL 文件。生成的 DLL 文件需要通过 YooAsset 的资源构建管线打包,上传到 CDN 服务器供玩家下载。

在版本管理方面,热更 DLL 的每个版本都应该有一个对应的版本号和一个构建时间戳。版本号建议采用语义化版本号格式:主版本号.次版本号.修订号。主版本号递增表示不兼容的 API 变更,次版本号递增表示增加功能但保持兼容,修订号递增表示问题修复。每次构建时,需要在版本配置文件中记录当前热更 DLL 的版本号和对应资源包的版本号,这样在运行时可以进行版本校验。

热更 DLL 的依赖管理也是一个容易出问题的环节。如果热更 DLL 引用了主工程中不存在的类型或方法,在解释执行时会抛出 MissingMethodException。因此,每次主工程发布后,所有正在开发中的热更 DLL 都需要重新编译,以确保引用的 AOT API 是最新版本。建议在 CI/CD 流水线中加入依赖检查步骤,自动检测热更 DLL 与主工程的兼容性。

2.5 AOT 泛化与补充元数据

HybridCLR 在处理泛型时有一个重要的限制:不能在热更代码中实例化 AOT 部分没有用过的泛型类型。这需要我们在 AOT 侧提前"预留"一些泛型实例。

/// <summary>
/// AOT 泛型预留:确保热更代码中使用的泛型类型在 AOT 侧有实例化记录
/// </summary>
public static class AOTGenericReserves
{
    /// <summary>
    /// 预留泛型方法调用,防止 HybridCLR 泛型实例化失败
    /// 此方法不需要实际调用,只需确保编译器生成对应的泛型代码
    /// </summary>
    public static void Reserve()
    {
        // 常用泛型集合预留
        new List<int>();
        new List<string>();
        new List<float>();
        new List<long>();
        new List<double>();
        new Dictionary<string, int>();
        new Dictionary<int, string>();
        new Dictionary<string, object>();

        // 常用泛型类型预留
        new Nullable<int>();
        new Nullable<float>();
        new Nullable<bool>();
        new Nullable<long>();

        // Task 泛型预留(如果使用 async/await)
        // Task<int>.Factory.StartNew(() => 0);
        // Task<string>.Factory.StartNew(() => "");

        // UnityEngine 常用泛型预留
        // new List<GameObject>();
        // new List<Transform>();
        // new Dictionary<string, GameObject>();
    }
}

三、同步热更代码与资源

3.1 同步热更的设计思路

在实际项目中,代码热更和资源热更往往是同时进行的。如果代码和资源的版本不同步,会导致加载失败或运行时异常。

版本同步策略

策略 描述 优点 缺点
统一版本号 代码和资源使用同一个版本号 管理简单 代码小修改也需要全量更新
独立版本号 代码和资源各自维护版本号 灵活 版本兼容性管理复杂
资源版本继承代码版本 资源版本随代码版本递增 折中方案 仍需版本映射表

同步热更的完整流程

[启动游戏]
    │
    ▼
[初始化 YooAsset]
    │
    ▼
[检查资源版本] ──── 有更新 ────▶ [下载更新资源]
    │                                │
    ▼                                ▼
[检查代码版本] ──── 有更新 ────▶ [下载最新 DLL]
    │                                │
    ▼                                ▼
[加载热更 DLL] ◀──────────────────────┘
    │
    ▼
[调用热更入口]
    │
    ▼
[进入游戏]

3.2 同步热更管理器实现

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using YooAsset;
using System;

/// <summary>
/// 同步热更管理器:协调代码和资源的版本检查与下载
/// </summary>
public class SyncHotUpdateManager : MonoBehaviour
{
    [Header("YooAsset 配置")]
    public string packageName = "DefaultPackage";

    [Header("版本管理")]
    public string versionConfigLocation = "Config/version_config.json";

    [System.Serializable]
    public class VersionConfig
    {
        public string resourceVersion;    // 资源版本号
        public string codeVersion;        // 代码版本号
        public string hotfixDLLVersion;   // 热更 DLL 版本
        public List<string> requiredDLLs; // 必需的 DLL 列表
    }

    private ResourcePackage resourcePackage;
    private VersionConfig remoteVersionConfig;
    private VersionConfig localVersionConfig;

    // 状态
    public enum UpdatePhase
    {
        Idle,
        CheckingResource,
        CheckingCode,
        DownloadingResource,
        DownloadingCode,
        LoadingDLL,
        Complete,
        Failed
    }

    public UpdatePhase CurrentPhase { get; private set; } = UpdatePhase.Idle;
    public float OverallProgress { get; private set; }
    public bool HasError { get; private set; }
    public string ErrorMessage { get; private set; }

    public event Action<UpdatePhase> OnPhaseChanged;
    public event Action<float> OnProgressUpdated;
    public event Action OnUpdateComplete;
    public event Action<string> OnUpdateFailed;

    private HybridCLRManager hybridCLRManager;

    private void Start()
    {
        hybridCLRManager = GetComponent<HybridCLRManager>();
        if (hybridCLRManager == null)
        {
            hybridCLRManager = gameObject.AddComponent<HybridCLRManager>();
        }

        resourcePackage = YooAssets.GetPackage(packageName);
    }

    /// <summary>
    /// 开始完整的同步热更流程
    /// </summary>
    public IEnumerator StartHotUpdate()
    {
        HasError = false;
        CurrentPhase = UpdatePhase.CheckingResource;
        OnPhaseChanged?.Invoke(CurrentPhase);

        // 第一步:检查资源版本
        yield return StartCoroutine(CheckResourceVersion());
        if (HasError) yield break;

        // 第二步:下载更新资源
        CurrentPhase = UpdatePhase.DownloadingResource;
        OnPhaseChanged?.Invoke(CurrentPhase);
        yield return StartCoroutine(DownloadUpdatedResources());
        if (HasError) yield break;

        // 第三步:检查代码版本
        CurrentPhase = UpdatePhase.CheckingCode;
        OnPhaseChanged?.Invoke(CurrentPhase);
        yield return StartCoroutine(CheckCodeVersion());
        if (HasError) yield break;

        // 第四步:下载热更 DLL
        CurrentPhase = UpdatePhase.DownloadingCode;
        OnPhaseChanged?.Invoke(CurrentPhase);
        yield return StartCoroutine(DownloadHotfixDLLs());
        if (HasError) yield break;

        // 第五步:加载热更 DLL
        CurrentPhase = UpdatePhase.LoadingDLL;
        OnPhaseChanged?.Invoke(CurrentPhase);
        yield return StartCoroutine(hybridCLRManager.LoadHotfixDLLs());

        if (hybridCLRManager.IsLoaded)
        {
            CurrentPhase = UpdatePhase.Complete;
            OnPhaseChanged?.Invoke(CurrentPhase);
            OnUpdateComplete?.Invoke();
            Debug.Log("[SyncUpdate] 完整热更新流程完成");
        }
        else
        {
            OnUpdateFailed?.Invoke(hybridCLRManager.LastError);
        }
    }

    /// <summary>
    /// 检查资源版本
    /// </summary>
    private IEnumerator CheckResourceVersion()
    {
        OverallProgress = 0.05f;
        OnProgressUpdated?.Invoke(OverallProgress);
        Debug.Log("[SyncUpdate] 检查资源版本...");

        var updateOp = resourcePackage.UpdatePackageVersionAsync();
        yield return updateOp;

        if (updateOp.Status == EOperationStatus.Succeed)
        {
            string remoteVersion = updateOp.PackageVersion;
            string localVersion = resourcePackage.GetPackageVersion();

            Debug.Log($"[SyncUpdate] 本地版本: {localVersion}, 远程版本: {remoteVersion}");

            if (localVersion != remoteVersion)
            {
                Debug.Log($"[SyncUpdate] 检测到资源更新: {localVersion} -> {remoteVersion}");
            }
            else
            {
                Debug.Log("[SyncUpdate] 资源已是最新版本");
            }
        }
        else
        {
            HasError = true;
            ErrorMessage = $"资源版本检查失败: {updateOp.Error}";
            Debug.LogError($"[SyncUpdate] {ErrorMessage}");
            OnUpdateFailed?.Invoke(ErrorMessage);
        }
    }

    /// <summary>
    /// 下载更新资源
    /// </summary>
    private IEnumerator DownloadUpdatedResources()
    {
        var downloader = resourcePackage.CreateResourceDownloader();

        if (downloader.TotalDownloadCount == 0)
        {
            OverallProgress = 0.35f;
            OnProgressUpdated?.Invoke(OverallProgress);
            Debug.Log("[SyncUpdate] 无需下载资源");
            yield break;
        }

        Debug.Log($"[SyncUpdate] 需要下载 {downloader.TotalDownloadCount} 个资源文件,共 " +
            $"{downloader.TotalDownloadBytes / (1024f * 1024f):F2}MB");

        downloader.OnDownloadProgressCallback += (totalCount, completedCount, totalBytes, downloadedBytes) =>
        {
            float downloadProgress = (float)completedCount / totalCount;
            // 资源下载占整体进度的 30%(从 5% 到 35%)
            OverallProgress = 0.05f + downloadProgress * 0.30f;
            OnProgressUpdated?.Invoke(OverallProgress);
        };

        downloader.BeginDownload();
        yield return downloader;

        if (downloader.Status == EOperationStatus.Succeed)
        {
            OverallProgress = 0.35f;
            OnProgressUpdated?.Invoke(OverallProgress);
            Debug.Log("[SyncUpdate] 资源下载完成");
        }
        else
        {
            HasError = true;
            ErrorMessage = $"资源下载失败: {downloader.Error}";
            Debug.LogError($"[SyncUpdate] {ErrorMessage}");
            OnUpdateFailed?.Invoke(ErrorMessage);
        }
    }

    /// <summary>
    /// 检查代码版本(通过读取远程的版本配置文件)
    /// </summary>
    private IEnumerator CheckCodeVersion()
    {
        OverallProgress = 0.40f;
        OnProgressUpdated?.Invoke(OverallProgress);
        Debug.Log("[SyncUpdate] 检查代码版本...");

        var handle = resourcePackage.LoadAssetAsync<TextAsset>(versionConfigLocation);
        yield return handle;

        if (handle.Status == EOperationStatus.Succeed)
        {
            TextAsset configAsset = handle.AssetObject as TextAsset;
            if (configAsset != null)
            {
                remoteVersionConfig = JsonUtility.FromJson<VersionConfig>(configAsset.text);
                LoadLocalVersionConfig();

                Debug.Log($"[SyncUpdate] 代码版本 - 本地: {localVersionConfig?.codeVersion}, " +
                    $"远程: {remoteVersionConfig.codeVersion}");
            }

            handle.Release();
        }
        else
        {
            Debug.LogWarning("[SyncUpdate] 无法获取远程版本配置,使用本地代码版本");
        }

        OverallProgress = 0.45f;
        OnProgressUpdated?.Invoke(OverallProgress);
    }

    /// <summary>
    /// 下载热更 DLL 文件
    /// </summary>
    private IEnumerator DownloadHotfixDLLs()
    {
        if (remoteVersionConfig == null || remoteVersionConfig.requiredDLLs == null)
        {
            OverallProgress = 0.60f;
            OnProgressUpdated?.Invoke(OverallProgress);
            Debug.Log("[SyncUpdate] 无需下载热更 DLL");
            yield break;
        }

        // 创建只下载 DLL 文件的下载器
        string[] dllLocations = remoteVersionConfig.requiredDLLs
            .Select(dll => $"HotfixDLL/{dll}")
            .ToArray();

        var downloader = resourcePackage.CreateResourceDownloader(dllLocations);

        if (downloader.TotalDownloadCount == 0)
        {
            OverallProgress = 0.60f;
            OnProgressUpdated?.Invoke(OverallProgress);
            Debug.Log("[SyncUpdate] 热更 DLL 已是最新");
            yield break;
        }

        Debug.Log($"[SyncUpdate] 需要下载 {downloader.TotalDownloadCount} 个 DLL 文件");

        downloader.OnDownloadProgressCallback += (totalCount, completedCount, totalBytes, downloadedBytes) =>
        {
            float dllProgress = (float)completedCount / totalCount;
            OverallProgress = 0.45f + dllProgress * 0.15f;
            OnProgressUpdated?.Invoke(OverallProgress);
        };

        downloader.BeginDownload();
        yield return downloader;

        if (downloader.Status == EOperationStatus.Succeed)
        {
            OverallProgress = 0.60f;
            OnProgressUpdated?.Invoke(OverallProgress);
            Debug.Log("[SyncUpdate] 热更 DLL 下载完成");
        }
        else
        {
            HasError = true;
            ErrorMessage = $"DLL 下载失败: {downloader.Error}";
            Debug.LogError($"[SyncUpdate] {ErrorMessage}");
            OnUpdateFailed?.Invoke(ErrorMessage);
        }
    }

    private void LoadLocalVersionConfig()
    {
        // 从本地持久化存储加载版本配置
        string json = PlayerPrefs.GetString("LocalVersionConfig", "");
        if (!string.IsNullOrEmpty(json))
        {
            localVersionConfig = JsonUtility.FromJson<VersionConfig>(json);
        }
        else
        {
            localVersionConfig = new VersionConfig
            {
                resourceVersion = "0.0.0",
                codeVersion = "0.0.0",
                hotfixDLLVersion = "0.0.0"
            };
        }
    }

    public void SaveLocalVersionConfig()
    {
        if (remoteVersionConfig != null)
        {
            string json = JsonUtility.ToJson(remoteVersionConfig);
            PlayerPrefs.SetString("LocalVersionConfig", json);
            PlayerPrefs.Save();
        }
    }
}

3.3 热更启动流程的完整时序

为了帮助读者更好地理解整个同步热更流程,下面给出了一个完整的启动时序图。这个时序图展示了从用户点击游戏图标到进入游戏主界面的全过程,每个阶段的责任方和耗时预估都清晰标注出来。

从时序上看,整个启动流程可以分为三个阶段:首先是框架初始化阶段,包括 YooAsset 和 HybridCLR 运行时的初始化,这个阶段通常在 0.5 到 1 秒内完成;其次是版本检测和资源下载阶段,这个阶段的时间取决于更新量的大小和网络速度,如果不需要更新则可以在 1 秒内完成;最后是热更 DLL 加载和游戏入口调用阶段,这个阶段通常在 0.2 到 0.5 秒内完成。

在实际项目中,启动流程的设计需要特别注意以下几点:第一,版本检测和资源下载必须在 Loading 界面显示之后再进行,不能让玩家看到黑屏等待;第二,下载进度需要实时反馈给 Loading 界面,使用户知道当前的进度状态;第三,如果下载失败或者加载 DLL 失败,需要有合理的错误提示和重试机制,不能直接崩溃退出;第四,热更完成后的第一帧不要做大量的资源加载操作,以免造成明显的卡顿。

一个值得推荐的做法是在热更入口 Main 方法中只做轻量级的初始化工作,如 UI 管理器的创建和配置文件的加载,而将重量的业务逻辑延迟到游戏主循环的第一帧或者使用协程分帧执行。这样可以确保热更完成后的进入体验足够流畅。

3.4 热更入口与业务分离

热更代码的入口设计需要遵循"薄入口"原则,即主工程只负责加载和调用入口方法,具体的业务逻辑全部放在热更 DLL 中:

// ========== 主工程(AOT)==========
// 这部分代码编译在主 DLL 中,通过 IL2CPP 编译为原生代码

/// <summary>
/// 游戏启动入口(AOT 侧)
/// 只负责初始化框架和加载热更代码
/// </summary>
public class GameLauncher : MonoBehaviour
{
    private SyncHotUpdateManager hotUpdateManager;
    private HybridCLRManager hybridCLRManager;

    private void Start()
    {
        // 1. 初始化 YooAsset
        InitializeYooAsset();

        // 2. 初始化框架组件
        hotUpdateManager = gameObject.AddComponent<SyncHotUpdateManager>();
        hybridCLRManager = gameObject.AddComponent<HybridCLRManager>();

        // 3. 启动热更流程
        StartCoroutine(StartupFlow());
    }

    private IEnumerator StartupFlow()
    {
        // 显示 Loading UI
        ShowLoadingUI();

        // 执行热更新
        yield return StartCoroutine(hotUpdateManager.StartHotUpdate());

        if (hotUpdateManager.HasError)
        {
            ShowErrorUI(hotUpdateManager.ErrorMessage);
            yield break;
        }

        // 调用热更入口
        hybridCLRManager.InvokeHotfixEntry("Main");

        // 隐藏 Loading UI
        HideLoadingUI();
    }

    private void InitializeYooAsset()
    {
        YooAssets.Initialize();
        var package = YooAssets.CreatePackage("DefaultPackage");

        var initParameters = new ResourceDownloaderOperation();
        // 根据平台配置初始化参数
        // Android/iOS 使用 Sandbox 模式,WebGL 使用 WebRemote 模式
        var initOp = package.InitializeAsync(initParameters);
        // 实际项目中需要等待初始化完成
    }

    private void ShowLoadingUI() { /* 实现省略 */ }
    private void HideLoadingUI() { /* 实现省略 */ }
    private void ShowErrorUI(string error) { /* 实现省略 */ }
}

// ========== 热更工程(Interpreter)==========
// 这部分代码编译为 Hotfix.dll,运行时由 HybridCLR 解释执行

namespace Hotfix
{
    /// <summary>
    /// 热更入口(Interpreter 侧)
    /// 所有业务逻辑从这里开始
    /// </summary>
    public static class HotfixEntry
    {
        private static bool isInitialized = false;

        public static void Main()
        {
            if (isInitialized)
            {
                Debug.Log("[Hotfix] 热更代码已初始化,跳过重复初始化");
                return;
            }

            Debug.Log("[Hotfix] 热更代码入口启动");
            isInitialized = true;

            // 初始化热更模块
            var uiManager = new UIManager();
            var sceneManager = new SceneManager();

            // 加载主界面
            uiManager.ShowMainUI();

            // 进入默认场景
            sceneManager.LoadScene("MainCity");
        }
    }
}

四、差量更新流程

4.1 差量更新原理

差量更新的核心思想是:只下载发生变化的部分,而不是每次都全量下载。YooAsset 的差量更新机制基于资源包的版本对比:

场景 全量更新 差量更新
首次安装 下载所有资源 下载所有资源(无差异基准)
小版本更新 重新下载所有资源 仅下载变更的资源文件
大版本更新 重新下载所有资源 下载变更 + 新增的资源文件
回滚版本 重新下载所有资源 下载回滚所需的资源文件

4.2 YooAsset 差量更新配置

/// <summary>
/// 差量更新配置器:控制 YooAsset 的差量更新行为
/// </summary>
public class DeltaUpdateConfigurator
{
    /// <summary>
    /// 配置差量更新参数
    /// </summary>
    public static void ConfigureDeltaUpdate(ResourcePackage package)
    {
        // YooAsset 的差量更新主要依赖以下几个关键配置:

        // 1. 版本对比模式
        // - Full: 全量对比(耗时较长但最精确)
        // - Incremental: 增量对比(快速但依赖版本链)
        // 推荐使用 Incremental 模式

        // 2. 资源包构建时的差量包生成
        // 在 YooAsset Build Pipeline 中启用:
        // - Enable Delta Build: 启用差量构建
        // - Delta Step: 差量步长(每 N 个版本存一个全量基线)

        Debug.Log("[DeltaUpdate] 差量更新配置完成");
    }

    /// <summary>
    /// 获取差量下载摘要
    /// </summary>
    public static string GetDeltaSummary(DownloaderOperation downloader)
    {
        return $"差量更新摘要:
" +
               $"文件数: {downloader.TotalDownloadCount}
" +
               $"总量: {downloader.TotalDownloadBytes / (1024f * 1024f):F2}MB
" +
               $"预估耗时: {EstimateDownloadTime(downloader.TotalDownloadBytes)}";
    }

    private static string EstimateDownloadTime(long bytes)
    {
        // 假设平均下载速度为 2MB/s
        float seconds = bytes / (2f * 1024f * 1024f);
        if (seconds < 60)
            return $"{seconds:F0} 秒";
        else
            return $"{seconds / 60:F1} 分钟";
    }
}

4.3 差量更新实践

/// <summary>
/// 差量更新控制器:提供更细粒度的差量更新控制
/// </summary>
public class DeltaUpdateController : MonoBehaviour
{
    [Header("差量配置")]
    public string packageName = "DefaultPackage";
    public bool enableDelta = true;
    public bool verifyOnComplete = true;

    public enum DeltaUpdateResult
    {
        NoUpdate,        // 无需更新
        DeltaUpdate,     // 差量更新完成
        FullUpdate,      // 全量更新完成
        Failed           // 更新失败
    }

    public DeltaUpdateResult LastResult { get; private set; }
    public event Action<DeltaUpdateResult> OnUpdateFinished;

    /// <summary>
    /// 执行差量更新
    /// </summary>
    public IEnumerator PerformDeltaUpdate()
    {
        ResourcePackage package = YooAssets.GetPackage(packageName);

        // 步骤 1: 更新资源版本
        var versionOp = package.UpdatePackageVersionAsync();
        yield return versionOp;

        if (versionOp.Status != EOperationStatus.Succeed)
        {
            LastResult = DeltaUpdateResult.Failed;
            OnUpdateFinished?.Invoke(LastResult);
            yield break;
        }

        string remoteVersion = versionOp.PackageVersion;

        // 步骤 2: 更新资源清单(比较本地和远程的差异)
        var manifestOp = package.UpdatePackageManifestAsync(remoteVersion);
        yield return manifestOp;

        if (manifestOp.Status != EOperationStatus.Succeed)
        {
            LastResult = DeltaUpdateResult.Failed;
            OnUpdateFinished?.Invoke(LastResult);
            yield break;
        }

        // 步骤 3: 创建下载器(此时 YooAsset 自动计算差异)
        var downloader = package.CreateResourceDownloader();

        if (downloader.TotalDownloadCount == 0)
        {
            Debug.Log("[DeltaUpdate] 资源已是最新,无需更新");
            LastResult = DeltaUpdateResult.NoUpdate;
            OnUpdateFinished?.Invoke(LastResult);
            yield break;
        }

        Debug.Log($"[DeltaUpdate] 差量更新: {downloader.TotalDownloadCount} 个文件, " +
            $"{downloader.TotalDownloadBytes / (1024f * 1024f):F2}MB");

        // 步骤 4: 开始下载
        downloader.BeginDownload();
        yield return downloader;

        // 步骤 5: 完整性校验(可选)
        if (verifyOnComplete)
        {
            bool allValid = VerifyDownloadedAssets(package);
            if (!allValid)
            {
                Debug.LogError("[DeltaUpdate] 完整性校验失败");
                LastResult = DeltaUpdateResult.Failed;
                OnUpdateFinished?.Invoke(LastResult);
                yield break;
            }
        }

        if (downloader.Status == EOperationStatus.Succeed)
        {
            LastResult = DeltaUpdateResult.DeltaUpdate;
            Debug.Log("[DeltaUpdate] 差量更新完成");
        }
        else
        {
            LastResult = DeltaUpdateResult.Failed;
            Debug.LogError($"[DeltaUpdate] 差量更新失败: {downloader.Error}");
        }

        OnUpdateFinished?.Invoke(LastResult);
    }

    /// <summary>
    /// 校验已下载资源的完整性
    /// </summary>
    private bool VerifyDownloadedAssets(ResourcePackage package)
    {
        // 通过 YooAsset 提供的缓存校验接口
        // 检查所有已下载文件的 CRC
        Debug.Log("[DeltaUpdate] 开始完整性校验...");
        return true; // 实际项目中需实现完整的 CRC 校验逻辑
    }
}

4.4 断点续传与完整性校验

/// <summary>
/// 断点续传支持:YooAsset 内置支持断点续传,但我们可以增强它的可靠性
/// </summary>
public class ResumeDownloadEnhancer
{
    /// <summary>
    /// YooAsset 断点续传的关键机制:
    /// 1. 下载过程中会生成临时文件(.temp)
    /// 2. 下载完成后,临时文件重命名为正式文件
    /// 3. 再次下载时检测临时文件,从断点处继续下载
    /// 4. 服务器需要支持 HTTP Range 头
    ///
    /// 增强策略:
    /// 1. 定期记录下载断点信息到持久化存储
    /// 2. 应用被杀死后,再次启动时恢复断点
    /// 3. 对已完成下载的文件做 CRC 校验
    /// 4. 网络切换时保存断点,恢复后继续
    /// </summary>
    public static void SaveDownloadCheckpoint(DownloaderOperation downloader)
    {
        var checkpoint = new DownloadCheckpoint
        {
            timestamp = DateTime.Now.Ticks,
            completedCount = downloader.CurrentDownloadCount,
            totalCount = downloader.TotalDownloadCount,
            downloadedBytes = downloader.CurrentDownloadBytes,
            totalBytes = downloader.TotalDownloadBytes
        };

        string json = JsonUtility.ToJson(checkpoint);
        PlayerPrefs.SetString("DownloadCheckpoint", json);
        PlayerPrefs.Save();
    }

    [System.Serializable]
    public class DownloadCheckpoint
    {
        public long timestamp;
        public int completedCount;
        public int totalCount;
        public long downloadedBytes;
        public long totalBytes;
    }

    /// <summary>
    /// CRC 完整性校验器
    /// </summary>
    public class CRCValidator
    {
        private Dictionary<string, string> expectedCRCs = new Dictionary<string, string>();

        /// <summary>
        /// 加载预期的 CRC 表(从 YooAsset 的构建报告中获取)
        /// </summary>
        public void LoadExpectedCRCs(ResourcePackage package)
        {
            // 在实际项目中,CRC 信息包含在资源清单中
            // YooAsset 在下载完成后会自动进行 CRC 校验
            Debug.Log("[CRC] CRC 校验表已加载");
        }

        /// <summary>
        /// 校验单个文件
        /// </summary>
        public bool ValidateFile(string filePath, string expectedCRC)
        {
            if (!System.IO.File.Exists(filePath))
            {
                return false;
            }

            using (var stream = System.IO.File.OpenRead(filePath))
            {
                using (var md5 = System.Security.Cryptography.MD5.Create())
                {
                    byte[] hash = md5.ComputeHash(stream);
                    string actualCRC = BitConverter.ToString(hash).Replace("-", "").ToLower();
                    return actualCRC == expectedCRC.ToLower();
                }
            }
        }
    }
}

五、实战踩坑记录

5.1 DLL 加载失败

问题 原因 解决方案
FileNotFoundException 依赖的程序集未加载 确保所有依赖 DLL 都已下载并加载
BadImageFormatException DLL 文件损坏 重新下载,增加 CRC 校验
ReflectionTypeLoadException 类型加载失败 检查泛型预留代码是否完整
MissingMethodException 方法签名不匹配 确保主工程和热更工程的 API 版本一致
/// <summary>
/// DLL 加载安全的完整方案
/// </summary>
public class SafeDLLLoader
{
    /// <summary>
    /// 安全加载程序集,包含完整的异常处理和依赖解析
    /// </summary>
    public Assembly SafeLoadAssembly(byte[] dllBytes, string assemblyName)
    {
        try
        {
            // 方法 1: 直接从字节加载(推荐)
            Assembly assembly = Assembly.Load(dllBytes);
            Debug.Log($"[DLLLoader] 程序集加载成功: {assemblyName}");
            return assembly;
        }
        catch (BadImageFormatException ex)
        {
            Debug.LogError($"[DLLLoader] DLL 格式错误: {assemblyName}, {ex.Message}");
            Debug.LogError("[DLLLoader] 请检查: 1)DLL 文件是否完整 2)目标平台是否正确");
            return null;
        }
        catch (System.IO.FileLoadException ex)
        {
            Debug.LogError($"[DLLLoader] DLL 加载异常: {assemblyName}, {ex.Message}");
            Debug.LogError("[DLLLoader] 请检查: 程序集是否重复加载");
            return null;
        }
        catch (Exception ex)
        {
            Debug.LogError($"[DLLLoader] 未知错误: {assemblyName}, {ex.Message}");
            return null;
        }
    }

    /// <summary>
    /// 验证 DLL 的完整性(加载前检查)
    /// </summary>
    public bool ValidateDLLIntegrity(byte[] dllBytes)
    {
        if (dllBytes == null || dllBytes.Length == 0)
        {
            Debug.LogError("[DLLLoader] DLL 文件为空");
            return false;
        }

        // 检查 PE 头部标志
        // 有效的 .NET DLL 以 "MZ" 开头
        if (dllBytes.Length < 2 || dllBytes[0] != 0x4D || dllBytes[1] != 0x5A)
        {
            Debug.LogError("[DLLLoader] DLL 文件头部异常,不是有效的 PE 文件");
            return false;
        }

        return true;
    }
}

5.2 代码版本不一致

代码版本不一致是热更新中最隐蔽的问题之一。以下是常见场景:

场景 问题描述 解决方案
AOT API 变更 热更代码调用了 AOT 侧已删除的方法 保持 AOT 侧 API 向后兼容
热更 DLL 依赖错误 热更 DLL 引用了错误的 AOT DLL 版本 构建时锁定依赖版本
多 DLL 版本冲突 多个热更 DLL 引用了不同版本的同名类型 统一程序集版本号
序列化兼容 新增/删除字段导致序列化异常 使用 SerializeVersion 属性控制
/// <summary>
/// 版本兼容性检查器
/// </summary>
public class VersionCompatibilityChecker
{
    [System.Serializable]
    public class CompatibilityReport
    {
        public string mainVersion;          // 主工程版本
        public string hotfixVersion;        // 热更代码版本
        public string apiHash;              // API 签名哈希
        public List<string> breakingChanges; // 破坏性变更列表
        public bool isCompatible;
    }

    /// <summary>
    /// 检查热更 DLL 与主工程的兼容性
    /// </summary>
    public CompatibilityReport CheckCompatibility(Assembly hotfixAssembly, string mainVersion)
    {
        var report = new CompatibilityReport
        {
            mainVersion = mainVersion,
            isCompatible = true,
            breakingChanges = new List<string>()
        };

        // 检查热更程序集中引用的主工程类型
        foreach (var referencedAssembly in hotfixAssembly.GetReferencedAssemblies())
        {
            if (referencedAssembly.Name == "Assembly-CSharp")
            {
                // 比较版本号
                if (referencedAssembly.Version != null)
                {
                    report.hotfixVersion = referencedAssembly.Version.ToString();
                    if (referencedAssembly.Version.Major != GetMainVersionMajor(mainVersion))
                    {
                        report.isCompatible = false;
                        report.breakingChanges.Add($"主版本号不匹配: {referencedAssembly.Version} vs {mainVersion}");
                    }
                }
            }
        }

        return report;
    }

    private int GetMainVersionMajor(string version)
    {
        if (string.IsNullOrEmpty(version)) return 0;
        var parts = version.Split('.');
        if (parts.Length > 0 && int.TryParse(parts[0], out int major))
        {
            return major;
        }
        return 0;
    }
}

5.3 资源加载失败

错误类型 现象 排查步骤
AssetNotFound 资源路径不存在 检查 YooAsset 构建报告中的资源路径
BundleNotFound Bundle 缺失 检查 Bundle 是否被正确构建和上传
CRC Error 文件损坏 重新构建/上传资源
Version Mismatch 资源版本不匹配 检查版本号是否同步
/// <summary>
/// 资源加载诊断工具
/// </summary>
public static class AssetLoadDiagnostics
{
    /// <summary>
    /// 诊断资源加载失败的原因
    /// </summary>
    public static string DiagnoseLoadFailure(string location, ResourcePackage package)
    {
        var sb = new System.Text.StringBuilder();
        sb.AppendLine($"====== 资源加载诊断报告 ======");
        sb.AppendLine($"资源路径: {location}");
        sb.AppendLine($"当前包版本: {package.GetPackageVersion()}");

        // 1. 检查资源是否在包中
        bool hasAsset = package.CheckLocationValid(location);
        sb.AppendLine($"路径有效性: {hasAsset}");

        if (!hasAsset)
        {
            sb.AppendLine("[诊断] 资源路径无效,请检查:");
            sb.AppendLine("  - 资源是否已包含在构建中");
            sb.AppendLine("  - 路径大小写是否匹配");
            sb.AppendLine("  - 资源是否在正确的 Package 中");
        }

        // 2. 检查 Bundle 状态
        var bundleInfo = package.GetBundleInfo(location);
        if (bundleInfo != null)
        {
            sb.AppendLine($"主 Bundle: {bundleInfo.BundleName}");
            sb.AppendLine($"Bundle 大小: {bundleInfo.FileSize / 1024f:F1}KB");
        }
        else
        {
            sb.AppendLine("[诊断] 无法获取 Bundle 信息,资源未正确打包");
        }

        // 3. 提供修复建议
        sb.AppendLine("====== 修复建议 ======");
        sb.AppendLine("1. 重新执行 YooAsset Build Pipeline");
        sb.AppendLine("2. 上传新的资源包到 CDN");
        sb.AppendLine("3. 验证资源版本号是否递增");
        sb.AppendLine("4. 检查 CDN URL 配置是否正确");

        return sb.ToString();
    }
}

5.4 内存泄漏

热更代码中的内存泄漏比主工程更难追踪,因为调试信息有限。

/// <summary>
/// 热更代码内存泄漏检测工具
/// </summary>
public class HotfixMemoryTracker
{
    private class TypeReferenceCount
    {
        public int referenceCount;
        public float lastCheckTime;
    }

    private Dictionary<string, TypeReferenceCount> typeCounts = new Dictionary<string, TypeReferenceCount>();
    private float checkInterval = 10f;
    private float timer = 0f;

    /// <summary>
    /// 每帧调用,监控热更相关对象的引用数量
    /// </summary>
    public void Update()
    {
        timer += Time.deltaTime;
        if (timer < checkInterval) return;
        timer = 0f;

        // 扫描场景中所有热更相关的 MonoBehaviour
        var hotfixBehaviours = Resources.FindObjectsOfTypeAll<MonoBehaviour>();
        foreach (var behaviour in hotfixBehaviours)
        {
            string typeName = behaviour.GetType().FullName;
            if (!typeName.StartsWith("Hotfix.")) continue;

            if (!typeCounts.ContainsKey(typeName))
            {
                typeCounts[typeName] = new TypeReferenceCount();
            }

            var count = typeCounts[typeName];
            int currentCount = CountInstances(typeName);

            if (currentCount > count.referenceCount * 1.5f && count.referenceCount > 0)
            {
                Debug.LogWarning($"[MemTracker] 热更类型 {typeName} 引用数异常增长: " +
                    $"{count.referenceCount} -> {currentCount}");
            }

            count.referenceCount = currentCount;
            count.lastCheckTime = Time.time;
        }
    }

    private int CountInstances(string typeName)
    {
        int count = 0;
        var allObjects = Resources.FindObjectsOfTypeAll<MonoBehaviour>();
        foreach (var obj in allObjects)
        {
            if (obj.GetType().FullName == typeName)
            {
                count++;
            }
        }
        return count;
    }

    /// <summary>
    /// 生成内存泄漏报告
    /// </summary>
    public string GenerateReport()
    {
        var sb = new System.Text.StringBuilder();
        sb.AppendLine("===== 热更内存追踪报告 =====");

        foreach (var kvp in typeCounts)
        {
            sb.AppendLine($"类型: {kvp.Key}");
            sb.AppendLine($"  引用数: {kvp.Value.referenceCount}");
            sb.AppendLine($"  最后检测: {kvp.Value.lastCheckTime:F1}s");
        }

        return sb.ToString();
    }
}

5.5 最佳实践汇总

类别 最佳实践 说明
架构设计 薄入口原则 主工程只负责框架初始化,业务逻辑全部放在热更 DLL 中
版本管理 语义化版本号 Major.Minor.Patch 格式,每次热更递增 Patch
DLL 管理 独立 DLL 目录 热更 DLL 使用独立的 YooAsset 目录,与普通资源隔离
测试流程 先灰度后全量 小范围验证后再全量推送
监控告警 热更成功率统计 实时监控热更流程的每个阶段成功率
回滚方案 保留上一版本 下载新 DLL 前先备份当前版本

六、热更新安全性保障

6.1 热更新安全风险分析

热更新机制在提供便利的同时也引入了安全风险,必须建立完善的安全防护体系:

风险类型 风险描述 影响范围 防护措施
DLL 篡改 热更 DLL 被恶意替换 代码执行风险 签名校验 + CRC 验证
资源篡改 AB 包被替换或植入恶意内容 资源加载风险 资源加密 + 完整性校验
中间人攻击 CDN 响应被劫持 数据传输风险 HTTPS + 证书绑定
版本回滚 强制回滚到含漏洞的版本 安全漏洞 版本号白名单机制
降级攻击 攻击者伪造旧版本响应 绕过更新 最低版本强制更新

6.2 安全校验实现

/// <summary>
/// 热更新安全校验器:提供多层次的安全验证
/// </summary>
public class HotUpdateSecurityValidator
{
    [System.Serializable]
    public class SecurityConfig
    {
        public bool enableSignatureValidation = true;
        public bool enableCRCValidation = true;
        public bool enableVersionBlacklist = true;
        public string publicKeyPath = "Config/public_key.bytes";
        public string[] blacklistedVersions;
    }

    private SecurityConfig securityConfig;
    private Dictionary<string, string> fileCRCCache = new Dictionary<string, string>();

    /// <summary>
    /// 验证热更 DLL 的数字签名
    /// </summary>
    public bool ValidateDLLSignature(byte[] dllBytes, byte[] signature, byte[] publicKey)
    {
        if (!securityConfig.enableSignatureValidation)
        {
            return true;
        }

        try
        {
            using (var rsa = new System.Security.Cryptography.RSACryptoServiceProvider())
            {
                rsa.ImportCspBlob(publicKey);
                return rsa.VerifyData(dllBytes, System.Security.Cryptography.CryptoConfig
                    .MapNameToOID("SHA256"), signature);
            }
        }
        catch (Exception ex)
        {
            Debug.LogError($"[Security] DLL 签名验证异常: {ex.Message}");
            return false;
        }
    }

    /// <summary>
    /// 计算并验证文件 CRC
    /// </summary>
    public bool ValidateFileCRC(string filePath, string expectedCRC)
    {
        if (!securityConfig.enableCRCValidation)
        {
            return true;
        }

        if (!System.IO.File.Exists(filePath))
        {
            Debug.LogError($"[Security] 文件不存在: {filePath}");
            return false;
        }

        string actualCRC = ComputeFileCRC(filePath);
        bool isValid = actualCRC == expectedCRC.ToLower();

        if (!isValid)
        {
            Debug.LogError($"[Security] CRC 校验失败: {filePath}");
            Debug.LogError($"[Security] 期望: {expectedCRC}, 实际: {actualCRC}");
        }

        return isValid;
    }

    private string ComputeFileCRC(string filePath)
    {
        if (fileCRCCache.TryGetValue(filePath, out string cachedCRC))
        {
            return cachedCRC;
        }

        using (var stream = System.IO.File.OpenRead(filePath))
        {
            using (var md5 = System.Security.Cryptography.MD5.Create())
            {
                byte[] hash = md5.ComputeHash(stream);
                string crc = BitConverter.ToString(hash).Replace("-", "").ToLower();
                fileCRCCache[filePath] = crc;
                return crc;
            }
        }
    }

    /// <summary>
    /// 检查版本是否在黑名单中
    /// </summary>
    public bool IsVersionBlacklisted(string version)
    {
        if (!securityConfig.enableVersionBlacklist || securityConfig.blacklistedVersions == null)
        {
            return false;
        }

        foreach (string blacklisted in securityConfig.blacklistedVersions)
        {
            if (version.StartsWith(blacklisted))
            {
                Debug.LogWarning($"[Security] 版本 {version} 在黑名单中");
                return true;
            }
        }

        return false;
    }
}

6.3 热更新回滚机制

/// <summary>
/// 热更新回滚管理器
/// </summary>
public class HotUpdateRollbackManager
{
    private const string ROLLBACK_FLAG = "HotUpdate_RollbackFlag";
    private const string PREVIOUS_VERSION_KEY = "HotUpdate_PreviousVersion";

    /// <summary>
    /// 在更新前备份当前版本
    /// </summary>
    public static void BackupCurrentVersion()
    {
        string currentVersion = YooAssets.GetPackage("DefaultPackage").GetPackageVersion();
        PlayerPrefs.SetString(PREVIOUS_VERSION_KEY, currentVersion);
        PlayerPrefs.SetInt(ROLLBACK_FLAG, 1);
        PlayerPrefs.Save();

        Debug.Log($"[Rollback] 已备份当前版本: {currentVersion}");
    }

    /// <summary>
    /// 检查是否需要回滚(启动时检测)
    /// </summary>
    public static bool ShouldRollback()
    {
        bool needRollback = PlayerPrefs.GetInt(ROLLBACK_FLAG, 0) == 1;

        if (needRollback)
        {
            string previousVersion = PlayerPrefs.GetString(PREVIOUS_VERSION_KEY, "");
            Debug.LogWarning($"[Rollback] 检测到需要回滚到版本: {previousVersion}");
        }

        return needRollback;
    }

    /// <summary>
    /// 执行回滚操作
    /// </summary>
    public static IEnumerator ExecuteRollback()
    {
        Debug.Log("[Rollback] 开始执行回滚...");

        // 清除回滚标志
        PlayerPrefs.SetInt(ROLLBACK_FLAG, 0);
        PlayerPrefs.Save();

        // 清除当前版本的缓存
        var package = YooAssets.GetPackage("DefaultPackage");
        package.ClearAllCacheFiles();

        // 重新初始化为上一个版本
        var initOp = package.InitializeAsync(new ResourceDownloaderOperation());
        yield return initOp;

        Debug.Log("[Rollback] 回滚完成");
    }

    /// <summary>
    /// 标记更新成功(清除回滚标志)
    /// </summary>
    public static void MarkUpdateSuccess()
    {
        PlayerPrefs.SetInt(ROLLBACK_FLAG, 0);
        PlayerPrefs.Save();
        Debug.Log("[Rollback] 更新成功标记已设置");
    }
}

七、总结

7.1 本章要点回顾

本章完整地介绍了 YooAsset + HybridCLR 联合热更新的实施方案:

  1. HybridCLR 环境搭建:安装配置、泛型预留、DLL 加载流程
  2. 同步热更代码+资源:版本同步策略、同步热更管理器实现
  3. 差量更新流程:原理、配置、断点续传、完整性校验
  4. 实战踩坑记录:DLL 加载失败、版本不一致、资源加载失败、内存泄漏

6.2 架构决策总结

决策点 选择方案 理由
代码热更方案 HybridCLR 原生 C# 开发,性能最优
资源热更方案 YooAsset 全链路资源管理,差量更新支持好
版本同步策略 独立版本号 + 版本映射表 灵活性强,支持代码和资源独立更新
DLL 加载方式 Assembly.Load(byte[]) 完全内存加载,不依赖文件系统
回滚策略 版本号降级 + 全量重下 简单可靠

6.3 实践建议

  1. 热更流程需要在项目初期就设计好,后期再接入会面临大量架构调整
  2. 重视版本兼容性,AOT 侧的 API 一旦发布就要保持向后兼容
  3. DLL 文件一定要做完整性校验,网络传输可能导致文件损坏
  4. 灰度发布是最好的保险,永远不要直接全量推送热更包
  5. 做好回滚预案,热更失败时玩家体验不能受影响

上一篇:完整游戏项目搭建
下一篇:Android/iOS/WebGL/小游戏多平台发布

posted @ 2026-11-25 10:47  SmalBox  阅读(15)  评论(0)    收藏  举报