8.YooAsset结合HybridCLR代码热更新实践

8.YooAsset结合HybridCLR代码热更新实践


8.1 知识点

安装HybridCLR

安装IL2CPP

根据操作系统,安装过程中选择模块时,必须选中 Windows Build Support(IL2CPP)或Mac Build Support(IL2CPP)。

安装 com.code-philosophy.hybridclr 包

主菜单中点击Windows/Package Manager打开包管理器。如下图所示点击Add package from git URL…,填入[https://gitee.com/focus-creative-games/hybridclr_unity.git]或[https://github.com/focus-creative-games/hybridclr_unity.git]。


初始化 com.code-philosophy.hybridclr

打开菜单HybridCLR/Installer…, 点击安装按钮进行安装。 耐心等待30s左右,安装完成后会在最后打印 安装成功日志。

初始化Unity热更新项目

创建ConsoleToScreen.cs脚本

这个脚本对于演示热更新没有直接作用。它可以打印日志到屏幕上,方便定位错误。

创建 Assets/ConsoleToScreen.cs 脚本类,代码如下:

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

public class ConsoleToScreen : MonoBehaviour
{
    const int maxLines = 50;
    const int maxLineLength = 120;
    private string _logStr = "";

    private readonly List<string> _lines = new List<string>();

    public int fontSize = 15;

    void OnEnable() { Application.logMessageReceived += Log; }
    void OnDisable() { Application.logMessageReceived -= Log; }

    public void Log(string logString, string stackTrace, LogType type)
    {
        foreach (var line in logString.Split('\n'))
        {
            if (line.Length <= maxLineLength)
            {
                _lines.Add(line);
                continue;
            }
            var lineCount = line.Length / maxLineLength + 1;
            for (int i = 0; i < lineCount; i++)
            {
                if ((i + 1) * maxLineLength <= line.Length)
                {
                    _lines.Add(line.Substring(i * maxLineLength, maxLineLength));
                }
                else
                {
                    _lines.Add(line.Substring(i * maxLineLength, line.Length - i * maxLineLength));
                }
            }
        }
        if (_lines.Count > maxLines)
        {
            _lines.RemoveRange(0, _lines.Count - maxLines);
        }
        _logStr = string.Join("\n", _lines);
    }

    void OnGUI()
    {
        GUI.matrix = Matrix4x4.TRS(Vector3.zero, Quaternion.identity,
           new Vector3(Screen.width / 1200.0f, Screen.height / 800.0f, 1.0f));
        GUI.Label(new Rect(10, 10, 800, 370), _logStr, new GUIStyle() { fontSize = Math.Max(10, fontSize) });
    }
}

main场景创建ConsoleToScreen空对象挂上ConsoleToScreen脚本

创建 HotUpdate 热更新模块

创建 Assets/HotUpdate 目录,在目录下 右键 Create/Assembly Definition,创建一个名为HotUpdate的程序集模块

配置HybridCLR

打开菜单 HybridCLR/Settings, 在Hot Update Assemblies配置项中添加HotUpdate程序集,如下图:

打开PlayerSettings,进行配置


hybridclr包低于v4.0.0版本,需要关闭增量式GC(Use Incremental GC) 选项
Scripting Backend 切换为 IL2CPP
Api Compatability Level 切换为 .Net 4.x(Unity 2019-2020) 或 .Net Framework(Unity 2021+)

创建热更新脚本

创建 Assets/HotUpdate/Hello.cs 文件

using System.Collections;
using UnityEngine;

public class Hello
{
    public static void Run()
    {
        Debug.Log("Hello, HybridCLR");
    }
}

加载热更新程序集

创建Assets/LoadDll.cs脚本,然后在main场景中创建一个GameObject对象,挂载LoadDll脚本。

using System;
using System.Linq;
using System.Reflection;
using UnityEngine;
using YooAsset;


public class LoadDll : MonoBehaviour
{
    void Start()
    {
    #if !UNITY_EDITOR
        // 打包后非编辑器模式下

        // 原生Hybrid模拟
        // Assembly hotUpdateAss = Assembly.Load(File.ReadAllBytes($"{Application.streamingAssetsPath}/HotUpdate.dll.bytes"));

        // 使用YooAsset 
        var package = YooAssets.GetPackage("DefaultPackage");

        //HotUpdate.dll.bytes
        AssetHandle handle = package.LoadAssetSync<TextAsset>
            ("Assets/AB/HotDll/HotUpdate.dll.bytes");
        TextAsset text = handle.AssetObject as TextAsset;
        Assembly hotUpdateAss = Assembly.Load(text.bytes);

    #else
        // 编辑器模式下
        // Editor环境下,HotUpdate.dll.bytes已经被自动加载,不需要加载,重复加载反而会出问题。
        // Editor下无需加载,直接查找获得HotUpdate程序集
        Assembly hotUpdateAss =
            System.AppDomain.CurrentDomain.GetAssemblies().First(a => a.GetName().Name == "HotUpdate");
    #endif

        //得到Hello类调用函数
        Type type = hotUpdateAss.GetType("Hello");
        type.GetMethod("Run").Invoke(null, null);
    }
}

打包生成HotUpdate.dll

运行菜单 HybridCLR/Generate/All 进行必要的生成操作。这一步不可遗漏!!!

将{proj}/HybridCLRData/HotUpdateDlls/StandaloneWindows64(MacOS下为StandaloneMacXxx)目录下的HotUpdate.dll复制到Assets/AB/HotDll/HotUpdate.dll.bytes,注意,要加.bytes后缀!!!这样才能被加载!

YooAsset资源中加入HotUpdate.dll

MyYooAssetTest的UpdateDone函数中,只打开加载Main场景的代码

// 场景加载
string scenePath = "Assets/AB/Scene/Main.unity"; //
var sceneMode = UnityEngine.SceneManagement.LoadSceneMode.Single;
var physicsMode = LocalPhysicsMode.None;
bool suspendLoad = false;
SceneHandle handle = _package.LoadSceneAsync(scenePath, sceneMode, physicsMode, suspendLoad);
await handle.Task;
Debug.Log("Scene name is " + handle.SceneName);

打包运行

先打一次AB包,放入Version文件和Bytes文件到StreamingAssets/yoo/DefaultPackage下

生成的AB包放在本地资源服务器,启动服务器

打开Build Settings对话框,点击Build And Run,打包并且运行热更新示例工程。可以看到Hello, HybridCLR

测试热更新

修改Assets/HotUpdate/Hello.cs的Run函数中Debug.Log(“Hello, HybridCLR”);代码,改成Debug.Log(“Hello, Linwentao!!!!!!”);

public class Hello
{
    public static void Run()
    {
        Debug.Log("Hello, Linwentao!!!!!!");
    }
}

运行菜单命令HybridCLR/CompileDll/ActiveBulidTarget重新编译热更新代码。

将{proj}/HybridCLRData/HotUpdateDlls/StandaloneWindows64(MacOS下为StandaloneMacXxx)目录下的HotUpdate.dll复制替换掉工程中已经存在的HotUpdate.dll.bytes,也要加上后缀bytes

检查YooAsset资源引用没有丢失,重新用YooAsset打AB包,全部放到资源服务器上

重新运行之前打包好的PC包,发现打印语句变了,实现代码热更新!!


8.2 知识点代码

ConsoleToScreen.cs

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

public class ConsoleToScreen : MonoBehaviour
{
    const int maxLines = 50;
    const int maxLineLength = 120;
    private string _logStr = "";

    private readonly List<string> _lines = new List<string>();

    public int fontSize = 15;

    void OnEnable()
    {
        Application.logMessageReceived += Log;
    }

    void OnDisable()
    {
        Application.logMessageReceived -= Log;
    }

    public void Log(string logString, string stackTrace, LogType type)
    {
        foreach (var line in logString.Split('\n'))
        {
            if (line.Length <= maxLineLength)
            {
                _lines.Add(line);
                continue;
            }

            var lineCount = line.Length / maxLineLength + 1;
            for (int i = 0; i < lineCount; i++)
            {
                if ((i + 1) * maxLineLength <= line.Length)
                {
                    _lines.Add(line.Substring(i * maxLineLength, maxLineLength));
                }
                else
                {
                    _lines.Add(line.Substring(i * maxLineLength, line.Length - i * maxLineLength));
                }
            }
        }

        if (_lines.Count > maxLines)
        {
            _lines.RemoveRange(0, _lines.Count - maxLines);
        }

        _logStr = string.Join("\n", _lines);
    }

    void OnGUI()
    {
        GUI.matrix = Matrix4x4.TRS(Vector3.zero, Quaternion.identity,
            new Vector3(Screen.width / 1200.0f, Screen.height / 800.0f, 1.0f));
        GUI.Label(new Rect(10, 10, 800, 370), _logStr, new GUIStyle() { fontSize = Math.Max(10, fontSize) });
    }
}

LoadDll.cs

using System;
using System.Linq;
using System.Reflection;
using UnityEngine;
using YooAsset;


public class LoadDll : MonoBehaviour
{
    void Start()
    {
    #if !UNITY_EDITOR
        // 打包后非编辑器模式下

        // 原生Hybrid模拟
        // Assembly hotUpdateAss = Assembly.Load(File.ReadAllBytes($"{Application.streamingAssetsPath}/HotUpdate.dll.bytes"));

        // 使用YooAsset 
        var package = YooAssets.GetPackage("DefaultPackage");

        //HotUpdate.dll.bytes
        AssetHandle handle = package.LoadAssetSync<TextAsset>
            ("Assets/AB/HotDll/HotUpdate.dll.bytes");
        TextAsset text = handle.AssetObject as TextAsset;
        Assembly hotUpdateAss = Assembly.Load(text.bytes);

    #else
        // 编辑器模式下
        // Editor环境下,HotUpdate.dll.bytes已经被自动加载,不需要加载,重复加载反而会出问题。
        // Editor下无需加载,直接查找获得HotUpdate程序集
        Assembly hotUpdateAss =
            System.AppDomain.CurrentDomain.GetAssemblies().First(a => a.GetName().Name == "HotUpdate");
    #endif

        //得到Hello类调用函数
        Type type = hotUpdateAss.GetType("Hello");
        type.GetMethod("Run").Invoke(null, null);
    }
}

Hello.cs

using System.Collections;
using UnityEngine;

public class Hello
{
    public static void Run()
    {
        Debug.Log("Hello, Linwentao!!!!!!");
    }
}

MyYooAssetTest.cs

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

public class MyYooAssetTest : MonoBehaviour
{
    public EPlayMode playMode = EPlayMode.HostPlayMode; //运行模式
    public string packageName = "DefaultPackage"; //默认包名
    public string packageVersion = ""; //服务器资源版本号
    private ResourcePackage _package = null; //资源包对象

    //网络相关
    public string defaultHostServer = "http://127.0.0.1/CDN/PC/v1.0";
    public string fallbackHostServer = "http://127.0.0.1/CDN/PC/v1.0";

    //下载相关
    public int downloadingMaxNum = 10;
    public int filedTryAgain = 3;
    private ResourceDownloaderOperation _downloader;

    private void Awake()
    {
        DontDestroyOnLoad(gameObject);
    }


    IEnumerator Start()
    {
        yield return null;

        //1.初始化YooAsset
        YooAssets.Initialize();

        // 获取或创建资源包对象
        _package = YooAssets.TryGetPackage(packageName);
        if (_package == null)
        {
            _package = YooAssets.CreatePackage(packageName);
        }

        // 创建远端服务实例,用于资源请求
        IRemoteServices remoteServices = new RemoteServices(defaultHostServer, fallbackHostServer);

        // 创建联机模式参数,并设置内置及缓存文件系统参数
        HostPlayModeParameters createParameters = new HostPlayModeParameters
        {
            //创建内置文件系统参数
            BuildinFileSystemParameters = FileSystemParameters.CreateDefaultBuildinFileSystemParameters(),
            //创建缓存系统参数
            CacheFileSystemParameters = FileSystemParameters.CreateDefaultCacheFileSystemParameters(remoteServices,new FileOffsetDecryption())
        };

        //执行异步初始化
        InitializationOperation initializationOperation =
            _package.InitializeAsync(createParameters);
        yield return initializationOperation;

        // 处理初始化结果
        if (initializationOperation.Status != EOperationStatus.Succeed)
        {
            Debug.LogWarning(initializationOperation.Error);
        }
        else
        {
            Debug.Log("初始化成功-------------------------");
        }


        //2.获取资源版本
        // 发起异步版本请求
        RequestPackageVersionOperation operation = _package.RequestPackageVersionAsync();
        yield return operation;

        // 处理版本请求结果
        if (operation.Status != EOperationStatus.Succeed)
        {
            Debug.LogWarning(operation.Error);
        }
        else
        {
            Debug.Log($"请求的版本: {operation.PackageVersion}");
            packageVersion = operation.PackageVersion;
        }


        //3.获取文件清单
        UpdatePackageManifestOperation operationManifest = _package.UpdatePackageManifestAsync(packageVersion);
        yield return operationManifest;

        // 处理文件清单结果
        if (operationManifest.Status != EOperationStatus.Succeed)
        {
            Debug.LogWarning(operationManifest.Error);
        }
        else
        {
            Debug.Log("更新资源清单成功-------------------");
        }


        //4.创建下载器
        _downloader = _package.CreateResourceDownloader(downloadingMaxNum, filedTryAgain);
        if (_downloader.TotalDownloadCount == 0)
        {
            Debug.Log("没有需要更新的文件");
            UpdateDone();
            StartCoroutine(UpdateDoneCoroutine());
            yield break;
        }
        else
        {
            int count = _downloader.TotalDownloadCount;
            long bytes = _downloader.TotalDownloadBytes;
            Debug.Log($"需要更新{count}个文件, 大小是{bytes / 1024 / 1024}MB");
        }


        //5.开始下载
        _downloader.DownloadErrorCallback = DownloadErrorCallback; // 单个文件下载失败
        _downloader.DownloadUpdateCallback = DownloadUpdateCallback; // 下载进度更新
        _downloader.BeginDownload(); //开始下载
        yield return _downloader;


        if (_downloader.Status != EOperationStatus.Succeed)
        {
            Debug.LogWarning(operationManifest.Error);
            yield break;
        }
        else
        {
            Debug.Log("下载成功-------------------");
        }


        //6.清理文件
        // 清理未使用的文件
        var operationClear = _package.ClearCacheFilesAsync(EFileClearMode.ClearUnusedBundleFiles);
        // 添加清理完成回调
        operationClear.Completed += Operation_Completed;
    }


    //热更新结束
    private async void UpdateDone()
    {
        Debug.Log("热更新结束");

        //跳转场景

        //模拟资源加载
        // Sprite car = _package.LoadAssetSync<Sprite>("Assets/AB/Image/汽车.png")
        //     .AssetObject as Sprite;
        // // Sprite car = _package.LoadAssetSync<Sprite>("Assets/AB/Image/汽车")
        // //     .AssetObject as Sprite;//后缀名可以省略
        // GameObject go = new GameObject();
        // go.AddComponent<SpriteRenderer>().sprite = car;


        //异步委托资源加载
        // AssetHandle handle = _package.LoadAssetAsync<Sprite>("Assets/AB/Image/汽车");
        // handle.Completed += Handle_Completed;


        // task加载资源
        // AssetHandle handle = _package.LoadAssetAsync<Sprite>("Assets/AB/Image/汽车");
        // await handle.Task;
        //
        // Sprite car = handle.AssetObject as Sprite;
        // GameObject go = new GameObject();
        // go.AddComponent<SpriteRenderer>().sprite = car;


        //获取所有信息
        // AssetInfo[] assetInfos = package.GetAssetInfos("hot");
        // foreach (var assetInfo in assetInfos)
        // {
        //     Debug.Log(assetInfo.AssetPath);
        // }

        // 场景加载
        string scenePath = "Assets/AB/Scene/Main.unity"; //
        var sceneMode = UnityEngine.SceneManagement.LoadSceneMode.Single;
        var physicsMode = LocalPhysicsMode.None;
        bool suspendLoad = false;
        SceneHandle handle = _package.LoadSceneAsync(scenePath, sceneMode, physicsMode, suspendLoad);
        await handle.Task;
        Debug.Log("Scene name is " + handle.SceneName);


        //预制体加载和创建
        // AssetHandle handle = _package.LoadAssetAsync<GameObject>
        //     ("Assets/AB/Prefab/Car.prefab");
        // await handle.Task;
        // GameObject go1 =Instantiate(handle.AssetObject as GameObject);
        // Debug.Log("Prefab go1 name:" + go1.name);
        // GameObject go2 = handle.InstantiateSync();
        // Debug.Log("Prefab go2 name:" + go2.name);


        //图片子对象加载
        // SubAssetsHandle handle =
        //     _package.LoadSubAssetsAsync<Sprite>("Assets/AB/Image/Farms");
        // await handle.Task;
        // var sprite = handle.GetSubAssetObject<Sprite>("hen");
        // new GameObject().AddComponent<SpriteRenderer>().sprite = sprite;
        // Debug.Log("Sprite name: " + sprite.name);


        //卸载未使用的资源包
        // var operation = package.UnloadUnusedAssetsAsync();
        // await operation.Task;

        //强制卸载资源包
        // var operation = package.UnloadAllAssetsAsync();
        // await operation.Task;


        //卸载资源包中某个资源 (要未被引用的,否则无效)
        // package.TryUnloadUnusedAsset("Assets/GameRes/Panel/login.prefab");
        //
    }

    //热更新结束协程
    IEnumerator UpdateDoneCoroutine()
    {
        yield return null;
        // 协程方式加载资源
        // AssetHandle handle = _package.LoadAssetAsync<Sprite>("Assets/AB/Image/汽车");
        // yield return handle;
        // Sprite car = handle.AssetObject as Sprite;
        // GameObject go = new GameObject();
        // go.AddComponent<SpriteRenderer>().sprite = car;
    }

    // 单个文件下载失败
    public static void DownloadErrorCallback(DownloadErrorData errorData)
    {
        string fileName = errorData.FileName;
        string errorInfo = errorData.ErrorInfo;
        Debug.Log($"下载失败, 文件名: {fileName}, 错误信息: {errorInfo}");
    }

    // 下载进度更新
    public static void DownloadUpdateCallback(DownloadUpdateData updateData)
    {
        int totalDownloadCount = updateData.TotalDownloadCount;
        int currentDownloadCount = updateData.CurrentDownloadCount;
        long totalDownloadSizeBytes = updateData.TotalDownloadBytes;
        long currentDownloadSizeBytes = updateData.CurrentDownloadBytes;
        Debug.Log($"下载进度: {currentDownloadCount}/{totalDownloadCount}, " +
                  $"{currentDownloadSizeBytes / 1024}KB/{totalDownloadSizeBytes / 1024}KB");
    }

    //文件清理完成
    private void Operation_Completed(AsyncOperationBase obj)
    {
        UpdateDone();
        StartCoroutine(UpdateDoneCoroutine());
    }


    // 异步委托回调
    private void Handle_Completed(AssetHandle handle)
    {
        Sprite car = handle.AssetObject as Sprite;
        GameObject go = new GameObject();
        go.AddComponent<SpriteRenderer>().sprite = car;
    }
}


转载请注明来源,欢迎对文章中的引用来源进行考证,欢迎指出任何有错误或不够清晰的表达。可以在下面评论区评论,也可以邮件至 785293209@qq.com

×

喜欢就点赞,疼爱就打赏