如果开发的时候按之前的一个Hotfix工程,一个Unity工程,开发会很麻烦。因此我们可以把Hotfix部分的代码放入到Unity当中,并增加一个标记,到时候把这些代码整合成一个dll文件即可。
具体思路
ILRuntime的原理就是热更代码单独生成一个dll文件,然后Unity启动的时候读取这个dll文件,热更新的时候只需要热更dll文件即可。之前的Hotfix工程就是把工程内的代码导成dll文件,我们可以将这些代码放入到Unity当中,使用一个标记来和非热更代码区分开来,比如在文件夹或文件上加@Hotfix的后缀。然后我们可以用一个打dll的工具,把这热更的代码文件打成dll即可。这样操作之后就不需要两个工程来回切,方便了开发。
之前用Hotfix工程生成hotfix.dll的时候,是引用了Assembly-CSharp.dll文件,而当我们把Hotfix代码放入Unity中后,Assembly-CSharp.dll中也会包含这些代码,所以我们打hotfix.dll的时候不能使用它了。需要我们自己先将Unity中没有@Hotfix标记的代码编译成一个unity.dll文件,然后利用这个dll和标记了@Hotfix的代码编译成我们需要的hotfix.dll文件,即可。
整合项目
首先我们把Hotfix的脚本放到Unity当中,然后添加@Hotfix后缀用来做区分,如图
打DLL工具
然后去制作我们的打dll工具,新建一个控制台应用叫BuildDllTool
我们需要的参数有,Unity Assets目录的路径,生成的dll文件的导出路径,Unity一些系统dll文件的路径(例如UnityEngine.dll等),编译配置路径(这一块内容还不是很了解,因为也是网上找的代码,后面在研究研究。文件这里先分享下: 编译配置 提取码: xub3 ),编译选项。代码如下
using System;
using System.Threading;
namespace BuildDllTool
{
class Program
{
static void Main(string[] args)
{
if (args.Length == 5)
{
Console.WriteLine("Unity Asset 路径:" + args[0]);
Console.WriteLine("dll 输出路径:"+ args[1]);
Console.WriteLine("Unity 系统的 dll 文件路径:" + args[2]);
Console.WriteLine("编译配置路径:" + args[3]);
Console.WriteLine("编译选项:" + args[4]);
var result = ScriptBiuldToDll.Build(args[0], args[1], args[2], args[3], args[4]);
Console.WriteLine("退出");
}
else
{
Console.WriteLine("参数不匹配!");
Console.WriteLine("退出!");
}
Thread.Sleep(500);
System.Diagnostics.Process.GetCurrentProcess().Close();
}
}
}
编译dll的代码如下,
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
namespace BuildDllTool
{
class ScriptBiuldToDll
{
public enum BuildStatus
{
Success = 0,
Fail
}
static public BuildStatus Build(string unityAssetsPath, string dllPath, string unitySystemDllPath, string compilerDirectoryPath, string define)
{
//编译项目的base.dll
Console.WriteLine("准备编译dll 10%");
//清空dll的存放文件夹
if (Directory.Exists(dllPath))
{
Directory.Delete(dllPath, true);
}
Directory.CreateDirectory(dllPath);
//Unity 中存放脚本的文件
string[] searchPath = new string[] { "Scripts", "