文章目录
前言
一、HyBridCLR 准备工作
HyBridCLR文档地址:HyBridCLR
在看本文章之前,建议先把HyBridCLR文档全部浏览一遍,否则会忽视掉很多细节。
Unity编辑器必须选择 Windows Build Support(IL2CPP)或Mac Build Support(IL2CPP)。
Windows: Win下需要安装visual studio 2019或更高版本。安装时至少要包含 使用Unity的游戏开发 和 使用c++的游戏开发 组件。安装git
Mac: 要求MacOS版本 >= 12,xcode版本 >= 13,例如xcode 13.4.1, macos 12.4。
安装 git
二、使用步骤
1.通过URL导入Unity
gitee: https://gitee.com/focus-creative-games/hybridclr_unity.git
github:https://github.com/focus-creative-games/hybridclr_unity.git。
任选其一,输入,回车。
2.打开ProjectSetting
说明导入成功!
3.下载HyBridCLR代码
下载成功!
4.创建热更新DLL
将热更新DLL放入HyBridCLRSetting中
5.先Generate All一次。
完成后会显示一个文件夹,表示成功!:
三、代码测试
创建脚本LoadDll.cs,并挂在场景物体上。
using System;
using System.IO;
using System.Reflection;
using UnityEngine;
using System.Linq;
public class LoadDll : MonoBehaviour
{
// Start is called before the first frame update
private string hotUpdateDllName = "MySqlite";
void Start()
{
// Editor环境下,HotUpdate.dll.bytes已经被自动加载,不需要加载,重复加载反而会出问题。
#if !UNITY_EDITOR
Assembly hotUpdateAss = Assembly.Load(File.ReadAllBytes($"{Application.streamingAssetsPath}/{hotUpdateDllName}.dll.bytes"));
#else
// Editor下无需加载,直接查找获得HotUpdate程序集
Assembly hotUpdateAss = System.AppDomain.CurrentDomain.GetAssemblies().First(a => a.GetName().Name == hotUpdateDllName);
#endif
Type type = hotUpdateAss.GetType("HotUpdate");
type.GetMethod("Set").Invoke(null, null);
}
}
在MySqlite热更程序集下创建热更脚本HotUpdate.cs,也挂在场景物体上
using UnityEngine;
public class HotUpdate : MonoBehaviour
{
public static void Set()
{
Debug.Log("第一次打印");
}
}
四、打包测试
- 继续 HyBridCLR->Generate->All 一次。
- 编译热更dll HyBridCLR->CompileDll->ActiveBuildTarget
- 新建文件夹 StreamingAssets。
- 找热更dll。目录位置:同Assets目录中, HybridCLRData>HotUpdateDlls>StandaloneWindows64->MySqlite.dll
- 复制该dll,放到工程StreamingAssets下,并改名为:MySqlite.dll.bytes
- Build
- 运行build程序
- 查看日志
- 修改HotUpdate为:第二次打印
- 重新编译,也就是重新第二步操作
- 第四步,找到对应热更dll,这次应该复制dll到打包后的StreamingAssets文件夹下。
- 重新运行build。查看打印日志
- 热更完成。
注意事项
- AOT 不可以直接访问 HotFix层代码。如要访问, 使用 委托或反射
- HotFix层可以直接访问AOT层代码。
- 建议把不改变代码的插件 放在AOT层。
- Generate ALL 结束后 要重新Build
- extern 修饰的方法 只能放在 AOT 层。
- 不能使用 Resources 加载资源。否则不能热更新。如要热更新,只能AB包方式。