ILRuntime(二)整合Hotfix到Unity中,脚本生成dll文件

如果开发的时候按之前的一个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", "ThridPartys" };
            for (int i = 0; i < searchPath.Length; i++)
            {
                searchPath[i] = Path.Combine(unityAssetsPath, searchPath[i]);
            }

            //找出所有的脚本
            List<string> files = new List<string>();
            foreach (var s in searchPath)
            {
                var fs = Directory.GetFiles(s, "*.*", SearchOption.AllDirectories).ToList();
                var _fs = fs.FindAll(f =>
                {
                    var _f = f.ToLower();
                    var exten = Path.GetExtension(_f);
                    if ((!_f.Contains("editor")) && (exten.Equals(".dll") || exten.Equals(".cs")))
                    {
                        return true;
                    }
                    return false;
                });

                files.AddRange(_fs);
            }

            files = files.Distinct().ToList();
            for (int i = 0; i < files.Count; i++)
            {
                files[i] = files[i].Replace('/', '\\').Trim('\\');
            }

            Console.WriteLine("开始整理script 20%");

            //项目中用到的dll
            var refDlls = files.FindAll(f => f.EndsWith(".dll"));
            //unity内脚本,用于先生成unity的dll文件,供hotfix.dll编译用
            var unityCs = files.FindAll(f => !f.EndsWith(".dll") && !f.Contains("@Hotfix"));
            //热更脚本,用于生成hotfix.dll
            var hotfixCs = files.FindAll(f => !f.EndsWith(".dll") && f.Contains("@Hotfix"));

            //临时目录
            var tempDirect = "d:/bd_temp";
            if (Directory.Exists(tempDirect))
            {
                Directory.Delete(tempDirect, true);
            }
            Directory.CreateDirectory(tempDirect);

            //除去不需要引用的dll
            for (int i = refDlls.Count - 1; i >= 0; i--)
            {
                var str = refDlls[i];
                if (str.Contains("Editor") || str.Contains("iOS") || str.Contains("Android") || str.Contains("StreamingAssets"))
                {
                    refDlls.RemoveAt(i);
                }
            }

            //拷贝dll到临时目录
            for (int i = 0; i < refDlls.Count; i++)
            {
                var copyto = Path.Combine(tempDirect, Path.GetFileName(refDlls[i]));
                File.Copy(refDlls[i], copyto, true);
                refDlls[i] = copyto;
            }

            //添加系统的dll
            refDlls.Add("System.dll");
            refDlls.Add("System.Core.dll");
            refDlls.Add("System.XML.dll");
            refDlls.Add("System.Data.dll");

            //添加Unity系统的dll
            string[] dllPaths = unitySystemDllPath.Split(',');
            foreach (string dll in dllPaths)
            {
                var dllfile = Directory.GetFiles(dll, "*.dll", SearchOption.AllDirectories);
                foreach (var d in dllfile)
                {
                    if (Path.GetFileNameWithoutExtension(d).StartsWith("Assembly-CSharp"))
                    {
                        continue;
                    }
                    refDlls.Add(d);
                }
            }

            var unityDllPath = dllPath + "unity.dll";

            Console.WriteLine("复制编译代码 30%");

            //拷贝非热更的cs文件到临时目录
            for (int i = 0; i < unityCs.Count; i++)
            {
                var copyto = Path.Combine(tempDirect, Path.GetFileName(unityCs[i]));
                int count = 1;
                while (File.Exists(copyto))
                {
                    //为解决mono.exe error: 文件名太长问题
                    copyto = copyto.Replace(".cs", "") + count + ".cs";
                    count++;
                }

                File.Copy(unityCs[i], copyto);
                unityCs[i] = copyto;
            }

            //检测dll,移除无效dll
            for (int i = refDlls.Count - 1; i >= 0; i--)
            {
                var r = refDlls[i];
                if (File.Exists(r))
                {
                    var fs = File.ReadAllBytes(r);
                    try
                    {
                        var assm = Assembly.Load(fs);
                    }
                    catch
                    {
                        Console.WriteLine("移除无效的 dll :" + r);
                        refDlls.RemoveAt(i);
                    }
                }
            }

            Console.WriteLine("[1/2]开始编译 unity.dll 40%");

            BuildStatus unityResult = BuildStatus.Success;
            //编译 unity.dll
            try
            {
                unityResult = BuildDll(refDlls.ToArray(), unityCs.ToArray(), unityDllPath, compilerDirectoryPath, define);
            }
            catch (Exception e)
            {
                Console.WriteLine("unity.dll 编译失败:" + e);
                throw;
            }
            Console.WriteLine("[2/2]开始编译hotfix.dll 70%");

            //将unity.dll加入
            refDlls.Add(unityDllPath);

            //编译hotfix.dll
            var hotfixDllPath = dllPath + "hotfix.dll";
            BuildStatus hotfixResult = BuildStatus.Success;
            try
            {
                hotfixResult = BuildDll(refDlls.ToArray(), hotfixCs.ToArray(), hotfixDllPath, compilerDirectoryPath, define);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }

            Console.WriteLine("清理临时文件 95%");
            Directory.Delete(tempDirect, true);

            if (unityResult == BuildStatus.Success && unityResult == hotfixResult)
            {
                Console.WriteLine("编译成功!");
                return BuildStatus.Success;
            }
            else
            {
                Console.WriteLine("编译失败!");
                return BuildStatus.Fail;
            }
        }

        /// <summary>
        /// 编译dll
        /// </summary>
        static public BuildStatus BuildDll(string[] refAssemblies, string[] codefiles, string output, string compilerDirectoryPath, string define)
        {
            // 设定编译参数,DLL代表需要引入的Assemblies
            CompilerParameters cp = new CompilerParameters();
            cp.GenerateExecutable = false;
            //在内存中生成
            cp.GenerateInMemory = true;
            //生成调试信息
            if (define.IndexOf("IL_DEBUG") >= 0)
            {
                cp.IncludeDebugInformation = true;
            }
            else
            {
                cp.IncludeDebugInformation = false;
            }

            //cp.TempFiles = new TempFileCollection(".", true);
            cp.OutputAssembly = output;
            //warning和 error分开,不然各种warning当成error,改死你
            cp.TreatWarningsAsErrors = false;
            cp.WarningLevel = 1;
            //编译选项
            cp.CompilerOptions = "-langversion:latest /optimize /unsafe /define:" + define;

            if (refAssemblies != null)
            {
                foreach (var d in refAssemblies)
                {
                    cp.ReferencedAssemblies.Add(d);
                }
            }

            // 编译代理
            CodeDomProvider provider;
            if (string.IsNullOrEmpty(compilerDirectoryPath))
            {
                provider = CodeDomProvider.CreateProvider("CSharp");
            }
            else
            {
                provider = CodeDomProvider.CreateProvider("cs", new Dictionary<string, string> {
                    { "CompilerDirectoryPath", compilerDirectoryPath }
                });
            }

            CompilerResults cr = provider.CompileAssemblyFromFile(cp, codefiles);
            if (true == cr.Errors.HasErrors)
            {
                StringBuilder sb = new StringBuilder();
                foreach (CompilerError ce in cr.Errors)
                {
                    sb.Append(ce.ToString());
                    sb.Append(Environment.NewLine);
                }
                Console.WriteLine(sb);
            }
            else
            {
                return BuildStatus.Success;
            }
            return BuildStatus.Fail;
        }
    }
}

然后我们将其生成为exe程序,放到Unity项目中(例如:Unity项目/Tools/BuildHotfixDll文件夹下)。然后前面的编译配置也可放在该文件夹下。

 

Unity中调用

然后我们在Editor下添加菜单栏,用来调用我们的exe文件生成dll文件即可。我们在Editor目录下创建ILRuntimeBuildWindow.cs

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;
using UnityEditor;
using UnityEngine;
using Debug = UnityEngine.Debug;

namespace EditorTool
{
	public class ILRuntimeBuildWindow : EditorWindow
    {
        Vector2 mLogScroll;
        string mLogs = string.Empty;

        public void OnGUI()
        {
            GUILayout.BeginVertical();
            {
                GUILayout.Label("脚本打包");
                GUILayout.Space(5);
                GUILayout.BeginHorizontal();
                {
                    if (GUILayout.Button("1.编译 Hotfix.dll", GUILayout.Width(200), GUILayout.Height(30)))
                    {
                        mLogs = string.Empty;
                        string outpath = Application.streamingAssetsPath + "/hotfix_dll/";
                        BuildDLL(Application.dataPath + "/", outpath);
                        AssetDatabase.Refresh();
                    }
                }
                GUILayout.EndHorizontal();

                if (!string.IsNullOrEmpty(mLogs))
                {
                    mLogScroll = EditorGUILayout.BeginScrollView(mLogScroll, GUILayout.Height(400));
                    mLogs = EditorGUILayout.TextArea(mLogs);
                    EditorGUILayout.EndScrollView();
                }
            }
            GUILayout.EndVertical();
        }

        public void BuildDLL(string codeSource, string export, Action compileFinishedCallback = null, Action<string> outPutReceivedEvent = null)
        {
            string exePath = Environment.CurrentDirectory + "/Tools/BuildHotfixDll/BuildDllTool.exe";
            if (!File.Exists(exePath))
            {
                Debug.Log("编译工具不存在!");
                return;
            }

            //这里是引入unity所有引用的dll
            var u3dUI = string.Format(@"{0}\UnityExtensions\Unity", EditorApplication.applicationContentsPath);
            var u3dEngine = string.Format(@"{0}\Managed\UnityEngine", EditorApplication.applicationContentsPath);
            string libDll = Environment.CurrentDirectory + "/Library/ScriptAssemblies";
            string dllPath = u3dUI + "," + u3dEngine + "," + libDll;

            if (Directory.Exists(u3dUI) == false || Directory.Exists(u3dEngine) == false || Directory.Exists(libDll) == false)
            {
                EditorUtility.DisplayDialog("提示", "dll文件目录不存在,请修改ILRuntimeBuildWindow类中,u3dUI u3dEngine libDll的dll目录", "OK");
                return;
            }

            //编译配置文件目录
            string compilerDirectoryPath = Environment.CurrentDirectory + "/Tools/BuildHotfixDll/roslyn";

            var define = GetScriptingDefineSymbols();

            //执行exe文件,传递参数
            var p = new Process();
            p.EnableRaisingEvents = true;
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.CreateNoWindow = true;
            p.StartInfo.FileName = exePath;
            p.StartInfo.Arguments = string.Format("{0} {1} {2} {3} {4}", codeSource, export, dllPath, compilerDirectoryPath, define);
            p.Exited += (sender, e) =>
            {
                compileFinishedCallback?.Invoke();
            };
            p.OutputDataReceived += (sender, e) =>
            {
                mLogs += (e.Data + "\n");
            };
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.StandardOutputEncoding = Encoding.GetEncoding("gb2312");
            p.Start();
            p.BeginOutputReadLine();
            p.WaitForExit();
            EditorUtility.ClearProgressBar();
        }

        //获取编译选项
        string GetScriptingDefineSymbols()
        {
            List<string> validDefines = new List<string>();
            foreach (var define in EditorUserBuildSettings.activeScriptCompilationDefines)
            {
                if (!define.Contains("UNITY_EDITOR"))
                {
                    validDefines.Add(define);
                }
            }
            return string.Join(";", validDefines);
        }
    }
}

然后将其加入菜单栏中调用即可

using UnityEditor;

namespace EditorTool
{
	public class EditorToolMenu
	{
        [MenuItem("Tools/Build Hotfix Dll")]
        public static void ExecuteBuildDLL()
        {
            var window = (ILRuntimeBuildWindow)EditorWindow.GetWindow(typeof(ILRuntimeBuildWindow), false, "Build Hotfix Dll");
            window.Show();
        }
    }
}

选择菜单栏Tool ->Build Hotfix Dll打开我们的工具窗口,点击编译即可。编译成功如下

注意这样打出的dll是没有pdb文件的,因此我们可以在ILRuntimeHelp类中读取dll的代码处,去掉读取pdb的部分即可。

 

补充

1.若要将PackageManager中的内容打入到dll中,只需要在searchPath中添加Library/PackageCache的绝对路径即可。

  • 7
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 9
    评论
本课程主要是针对ILRuntime设计一个独立的脚本热更新框,框架的优势:1.将代码热更脱离Assetbundle资源热更,独立的部分更适用于各种不同的框架。2.加快项目的逻辑更新,bug修复.(后期修bug,多数情况下并不用动到资源,只需要更新脚本代码,无需重走资源打包发布流程,大大提升效率)3.提供热更模式和正常开发模式的快速切换接口,可以让队友像平常一样去开发.4.不依赖市面上的任何AB框架,完全兼容市面上各种不同的AB框架.5.重点:希望通过它,帮助你学习、了解ILRuntime真正在项目的应用.框架的将提供以下这些接口,这些接口将从0开始,在Unity里将C#脚本编译成dll,然后将dll放到服务器上,再将dll下载下来,进行加载,到最后从Unity主工程调用热更新的代码逻辑.1.Create hotfixdll接口将热更部分的代码 编译成dll生成dll版本配置(MD5)2.更新对比接口本地跟服务器的dll进行版本对比3.下载热更dll下载dll本身的文件下载版本记录文件4.加载热更dll加载dll实例化:AppDomain初始化:注册跨域继承适配器注册委托适配器LitJson重定向调用性能优化(CLR绑定功能)调用热更接口Hotfix.HotfixApplication.Main 进入热更逻辑5.ILMonoBehaviour用于监听组件的生命周期,实际是桥接(调用)热更的逻辑AwakeStartEnableUpdateLateUpdate.......6.添加其他常用的库DOTweenLitJsonSpineGoogle.ProtobufTextAnimation可以根据上面的方式,自行添加依赖的库... 
UnityGameFrameWork是一个非常优秀的游戏开发框架,而StarForce_ILRuntimeUnityGameFrameWork框架的一部分,用于实现热更新功能。下面是使用StarForce_ILRuntime实现热更新的步骤: 1. 在Unity创建一个新的项目,并且导入UnityGameFrameWork框架。 2. 下载StarForce_ILRuntime插件,并且导入到Unity。 3. 在Unity创建一个新的场景,并且添加一个空物体作为热更新管理器。 4. 在热更新管理器下创建一个新的C#脚本,并且添加以下代码: ``` public class HotfixManager : MonoSingleton<HotfixManager> { private ILRuntime.Runtime.Enviorment.AppDomain m_AppDomain = null; public void LoadHotfixAssembly(byte[] assBytes, byte[] pdbBytes) { if (m_AppDomain != null) { m_AppDomain = new ILRuntime.Runtime.Enviorment.AppDomain(); } using (MemoryStream ms = new MemoryStream(assBytes)) { using (MemoryStream pdb = new MemoryStream(pdbBytes)) { m_AppDomain.LoadAssembly(ms, pdb, new Mono.Cecil.Pdb.PdbReaderProvider()); } } m_AppDomain.Invoke("Hotfix.Init", "Init", null, null); } public T Invoke<T>(string typeName, string methodName, object instance, params object[] args) { var type = m_AppDomain.LoadedTypes[typeName]; var method = type.GetMethod(methodName); if (method == null) { Debug.LogError($"Can't find method: {methodName} in type: {typeName}"); return default(T); } return (T)method.Invoke(instance, args); } } ``` 5. 在Unity创建一个新的C#脚本,并且添加以下代码: ``` public static class Hotfix { public static void Init() { Debug.Log("Hotfix Init"); } public static int Add(int a, int b) { return a + b; } } ``` 6. 在Unity打包项目,并且生成一个DLL文件。 7. 使用ILRuntime的工具将DLL文件转换成bytes和pdb文件。 8. 加载bytes和pdb文件到热更新管理器: ``` var hotfixManager = HotfixManager.Instance; hotfixManager.LoadHotfixAssembly(assBytes, pdbBytes); ``` 9. 调用热更新代码: ``` var hotfixManager = HotfixManager.Instance; int result = hotfixManager.Invoke<int>("Hotfix", "Add", null, 1, 2); Debug.Log(result); ``` 以上就是使用StarForce_ILRuntime实现热更新的基本步骤。希望对你有所帮助。
评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值