Unity--解析ET6接入ILRuntime实现热更

2023-12-20 22:44

本文主要是介绍Unity--解析ET6接入ILRuntime实现热更,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

前言

1.介绍

ILRuntime项目为基于C#的平台(例如Unity)提供了一个纯C#实现,快速、方便且可靠的IL运行时,使得能够在不支持JIT的硬件环境(如iOS)能够实现代码的热更新。学习交流聚集地

介绍 — ILRuntime (http://ourpalm.github.io)

https://ourpalm.github.io/ILRuntime/public/v1/guide/index.html

ET是一个开源的游戏客户端(基于unity3d)服务端双端框架,服务端是使用C# .net core开发的分布式游戏服务端,其特点是开发效率高,性能强,双端共享逻辑代码,客户端服务端热更机制完善,同时支持可靠udp tcp websocket协议,支持服务端3D recast寻路等等 。

GitHub - egametang/ET: Unity3D Client And C# Server Framework

https://github.com/egametang/ET.git

2.接入ILRuntime

1.BuildAssemblieEditor.cs

构建codes.dll和codes.pdb到unity工程中并打上ab标签

Unity​www.bycwedu.com/promotion_channels/2146264125​编辑

public static class BuildAssemblieEditor{//dll复制到unity工程的路径private const string CodeDir = "Assets/Bundles/Code/";[MenuItem("Tools/BuildCode _F5")]public static void BuildCode(){//将codes目录下的所有cs文件打成code.dllBuildAssemblieEditor.BuildMuteAssembly("Code", new []{"Codes/Model/","Codes/ModelView/","Codes/Hotfix/","Codes/HotfixView/"}, Array.Empty<string>());//将code.dll复制到unity工程路径下并打上ab标签AfterCompiling();//刷新资源AssetDatabase.Refresh();}private static void BuildMuteAssembly(string assemblyName, string[] CodeDirectorys, string[] additionalReferences){//获取CodeDirectorys路径下的所有cs文件List<string> scripts = new List<string>();for (int i = 0; i < CodeDirectorys.Length; i++){DirectoryInfo dti = new DirectoryInfo(CodeDirectorys[i]);FileInfo[] fileInfos = dti.GetFiles("*.cs", System.IO.SearchOption.AllDirectories);for (int j = 0; j < fileInfos.Length; j++){scripts.Add(fileInfos[j].FullName);}}//编译dll的路径string dllPath = Path.Combine(Define.BuildOutputDir, $"{assemblyName}.dll");string pdbPath = Path.Combine(Define.BuildOutputDir, $"{assemblyName}.pdb");File.Delete(dllPath);File.Delete(pdbPath);Directory.CreateDirectory(Define.BuildOutputDir);AssemblyBuilder assemblyBuilder = new AssemblyBuilder(dllPath, scripts.ToArray());//启用UnSafe//assemblyBuilder.compilerOptions.AllowUnsafeCode = true;BuildTargetGroup buildTargetGroup = BuildPipeline.GetBuildTargetGroup(EditorUserBuildSettings.activeBuildTarget);assemblyBuilder.compilerOptions.ApiCompatibilityLevel = PlayerSettings.GetApiCompatibilityLevel(buildTargetGroup);// assemblyBuilder.compilerOptions.ApiCompatibilityLevel = ApiCompatibilityLevel.NET_4_6;//传递给程序集编译的其他程序集引用。assemblyBuilder.additionalReferences = additionalReferences;assemblyBuilder.flags = AssemblyBuilderFlags.DevelopmentBuild;//AssemblyBuilderFlags.None                 正常发布//AssemblyBuilderFlags.DevelopmentBuild     开发模式打包//AssemblyBuilderFlags.EditorAssembly       编辑器状态assemblyBuilder.referencesOptions = ReferencesOptions.UseEngineModules;assemblyBuilder.buildTarget = EditorUserBuildSettings.activeBuildTarget;assemblyBuilder.buildTargetGroup = buildTargetGroup;//编译开始回调assemblyBuilder.buildStarted += delegate(string assemblyPath) { Debug.LogFormat("build start:" + assemblyPath); };//编译结束回调assemblyBuilder.buildFinished += delegate(string assemblyPath, CompilerMessage[] compilerMessages){int errorCount = compilerMessages.Count(m => m.type == CompilerMessageType.Error);int warningCount = compilerMessages.Count(m => m.type == CompilerMessageType.Warning);Debug.LogFormat("Warnings: {0} - Errors: {1}", warningCount, errorCount);if (warningCount > 0){Debug.LogFormat("有{0}个Warning!!!", warningCount);}if (errorCount > 0){for (int i = 0; i < compilerMessages.Length; i++){if (compilerMessages[i].type == CompilerMessageType.Error){Debug.LogError(compilerMessages[i].message);}}}};//开始构建if (!assemblyBuilder.Build()){Debug.LogErrorFormat("build fail:" + assemblyBuilder.assemblyPath);return;}}private static void AfterCompiling(){//编译中while (EditorApplication.isCompiling){Debug.Log("Compiling wait1");// 主线程sleep并不影响编译线程Thread.Sleep(1000);Debug.Log("Compiling wait2");}Debug.Log("Compiling finish");//将dll和pdb拷贝到unity工程中Directory.CreateDirectory(CodeDir);File.Copy(Path.Combine(Define.BuildOutputDir, "Code.dll"), Path.Combine(CodeDir, "Code.dll.bytes"), true);File.Copy(Path.Combine(Define.BuildOutputDir, "Code.pdb"), Path.Combine(CodeDir, "Code.pdb.bytes"), true);AssetDatabase.Refresh();Debug.Log("copy Code.dll to Bundles/Code success!");// 设置ab包AssetImporter assetImporter1 = AssetImporter.GetAtPath("Assets/Bundles/Code/Code.dll.bytes");assetImporter1.assetBundleName = "Code.unity3d";AssetImporter assetImporter2 = AssetImporter.GetAtPath("Assets/Bundles/Code/Code.pdb.bytes");assetImporter2.assetBundleName = "Code.unity3d";AssetDatabase.Refresh();Debug.Log("set assetbundle success!");Debug.Log("build success!");}
}

2.CodeLoader.cs

初始化ILRuntime并启动热更层开始函数

case Define.CodeMode_ILRuntime:{//从ab包中加载dll和pdbDictionary<string, UnityEngine.Object> dictionary = AssetsBundleHelper.LoadBundle("code.unity3d");byte[] assBytes = ((TextAsset)dictionary["Code.dll"]).bytes;byte[] pdbBytes = ((TextAsset)dictionary["Code.pdb"]).bytes;AppDomain appDomain = new AppDomain();MemoryStream assStream = new MemoryStream(assBytes);MemoryStream pdbStream = new MemoryStream(pdbBytes);//ILRuntime加载程序集appDomain.LoadAssembly(assStream, pdbStream, new ILRuntime.Mono.Cecil.Pdb.PdbReaderProvider());//注册委托适配器等ILHelper.InitILRuntime(appDomain);//缓存所有热更反射类型this.allTypes = appDomain.LoadedTypes.Values.Select(x => x.ReflectionType).ToArray();//调用到热更层的entry类的start方法IStaticMethod start = new ILStaticMethod(appDomain, "ET.Entry", "Start", 0);start.Run();break;}

3.ILHelper.cs

注册重定向函数,委托,适配器,clr绑定

public static class ILHelper{public static List<Type> list = new List<Type>();public static void InitILRuntime(ILRuntime.Runtime.Enviorment.AppDomain appdomain){// 注册重定向函数list.Add(typeof(Dictionary<int, ILTypeInstance>));list.Add(typeof(Dictionary<int, int>));list.Add(typeof(Dictionary<object, object>));list.Add(typeof(Dictionary<int, object>));list.Add(typeof(Dictionary<long, object>));list.Add(typeof(Dictionary<long, int>));list.Add(typeof(Dictionary<int, long>));list.Add(typeof(Dictionary<string, long>));list.Add(typeof(Dictionary<string, int>));list.Add(typeof(Dictionary<string, object>));list.Add(typeof(List<ILTypeInstance>));list.Add(typeof(List<int>));list.Add(typeof(List<long>));list.Add(typeof(List<string>));list.Add(typeof(List<object>));list.Add(typeof(ListComponent<ILTypeInstance>));list.Add(typeof(ETTask<int>));list.Add(typeof(ETTask<long>));list.Add(typeof(ETTask<string>));list.Add(typeof(ETTask<object>));list.Add(typeof(ETTask<AssetBundle>));list.Add(typeof(ETTask<UnityEngine.Object[]>));list.Add(typeof(ListComponent<ETTask>));list.Add(typeof(ListComponent<Vector3>));// 注册委托appdomain.DelegateManager.RegisterMethodDelegate<List<object>>();appdomain.DelegateManager.RegisterMethodDelegate<object>();appdomain.DelegateManager.RegisterMethodDelegate<bool>();appdomain.DelegateManager.RegisterMethodDelegate<string>();appdomain.DelegateManager.RegisterMethodDelegate<float>();appdomain.DelegateManager.RegisterMethodDelegate<long, int>();appdomain.DelegateManager.RegisterMethodDelegate<long, MemoryStream>();appdomain.DelegateManager.RegisterMethodDelegate<long, IPEndPoint>();appdomain.DelegateManager.RegisterMethodDelegate<ILTypeInstance>();appdomain.DelegateManager.RegisterMethodDelegate<AsyncOperation>();appdomain.DelegateManager.RegisterFunctionDelegate<UnityEngine.Events.UnityAction>();appdomain.DelegateManager.RegisterFunctionDelegate<System.Object, ET.ETTask>();appdomain.DelegateManager.RegisterFunctionDelegate<ILTypeInstance, bool>();appdomain.DelegateManager.RegisterFunctionDelegate<System.Collections.Generic.KeyValuePair<System.String, System.Int32>, System.String>();appdomain.DelegateManager.RegisterFunctionDelegate<System.Collections.Generic.KeyValuePair<System.Int32, System.Int32>, System.Boolean>();appdomain.DelegateManager.RegisterFunctionDelegate<System.Collections.Generic.KeyValuePair<System.String, System.Int32>, System.Int32>();appdomain.DelegateManager.RegisterFunctionDelegate<List<int>, int>();appdomain.DelegateManager.RegisterFunctionDelegate<List<int>, bool>();appdomain.DelegateManager.RegisterFunctionDelegate<int, bool>();//Linqappdomain.DelegateManager.RegisterFunctionDelegate<int, int, int>();//Linqappdomain.DelegateManager.RegisterFunctionDelegate<KeyValuePair<int, List<int>>, bool>();appdomain.DelegateManager.RegisterFunctionDelegate<KeyValuePair<int, int>, KeyValuePair<int, int>, int>();appdomain.DelegateManager.RegisterDelegateConvertor<UnityEngine.Events.UnityAction>((act) =>{return new UnityEngine.Events.UnityAction(() =>{((Action)act)();});});appdomain.DelegateManager.RegisterDelegateConvertor<Comparison<KeyValuePair<int, int>>>((act) =>{return new Comparison<KeyValuePair<int, int>>((x, y) =>{return ((Func<KeyValuePair<int, int>, KeyValuePair<int, int>, int>)act)(x, y);});});// 注册适配器RegisterAdaptor(appdomain);//注册Json的CLRLitJson.JsonMapper.RegisterILRuntimeCLRRedirection(appdomain);//注册ProtoBuf的CLRPType.RegisterILRuntimeCLRRedirection(appdomain);//clr绑定初始化CLRBindings.Initialize(appdomain);}public static void RegisterAdaptor(ILRuntime.Runtime.Enviorment.AppDomain appdomain){//注册自己写的适配器appdomain.RegisterCrossBindingAdaptor(new IAsyncStateMachineClassInheritanceAdaptor());}}

发布于 2022-01-18 19:24

这篇关于Unity--解析ET6接入ILRuntime实现热更的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/517784

相关文章

Flutter实现文字镂空效果的详细步骤

《Flutter实现文字镂空效果的详细步骤》:本文主要介绍如何使用Flutter实现文字镂空效果,包括创建基础应用结构、实现自定义绘制器、构建UI界面以及实现颜色选择按钮等步骤,并详细解析了混合模... 目录引言实现原理开始实现步骤1:创建基础应用结构步骤2:创建主屏幕步骤3:实现自定义绘制器步骤4:构建U

SpringBoot中四种AOP实战应用场景及代码实现

《SpringBoot中四种AOP实战应用场景及代码实现》面向切面编程(AOP)是Spring框架的核心功能之一,它通过预编译和运行期动态代理实现程序功能的统一维护,在SpringBoot应用中,AO... 目录引言场景一:日志记录与性能监控业务需求实现方案使用示例扩展:MDC实现请求跟踪场景二:权限控制与

Android实现定时任务的几种方式汇总(附源码)

《Android实现定时任务的几种方式汇总(附源码)》在Android应用中,定时任务(ScheduledTask)的需求几乎无处不在:从定时刷新数据、定时备份、定时推送通知,到夜间静默下载、循环执行... 目录一、项目介绍1. 背景与意义二、相关基础知识与系统约束三、方案一:Handler.postDel

使用Python实现IP地址和端口状态检测与监控

《使用Python实现IP地址和端口状态检测与监控》在网络运维和服务器管理中,IP地址和端口的可用性监控是保障业务连续性的基础需求,本文将带你用Python从零打造一个高可用IP监控系统,感兴趣的小伙... 目录概述:为什么需要IP监控系统使用步骤说明1. 环境准备2. 系统部署3. 核心功能配置系统效果展

Python实现微信自动锁定工具

《Python实现微信自动锁定工具》在数字化办公时代,微信已成为职场沟通的重要工具,但临时离开时忘记锁屏可能导致敏感信息泄露,下面我们就来看看如何使用Python打造一个微信自动锁定工具吧... 目录引言:当微信隐私遇到自动化守护效果展示核心功能全景图技术亮点深度解析1. 无操作检测引擎2. 微信路径智能获

Python中pywin32 常用窗口操作的实现

《Python中pywin32常用窗口操作的实现》本文主要介绍了Python中pywin32常用窗口操作的实现,pywin32主要的作用是供Python开发者快速调用WindowsAPI的一个... 目录获取窗口句柄获取最前端窗口句柄获取指定坐标处的窗口根据窗口的完整标题匹配获取句柄根据窗口的类别匹配获取句

在 Spring Boot 中实现异常处理最佳实践

《在SpringBoot中实现异常处理最佳实践》本文介绍如何在SpringBoot中实现异常处理,涵盖核心概念、实现方法、与先前查询的集成、性能分析、常见问题和最佳实践,感兴趣的朋友一起看看吧... 目录一、Spring Boot 异常处理的背景与核心概念1.1 为什么需要异常处理?1.2 Spring B

Python位移操作和位运算的实现示例

《Python位移操作和位运算的实现示例》本文主要介绍了Python位移操作和位运算的实现示例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一... 目录1. 位移操作1.1 左移操作 (<<)1.2 右移操作 (>>)注意事项:2. 位运算2.1

如何在 Spring Boot 中实现 FreeMarker 模板

《如何在SpringBoot中实现FreeMarker模板》FreeMarker是一种功能强大、轻量级的模板引擎,用于在Java应用中生成动态文本输出(如HTML、XML、邮件内容等),本文... 目录什么是 FreeMarker 模板?在 Spring Boot 中实现 FreeMarker 模板1. 环

Qt实现网络数据解析的方法总结

《Qt实现网络数据解析的方法总结》在Qt中解析网络数据通常涉及接收原始字节流,并将其转换为有意义的应用层数据,这篇文章为大家介绍了详细步骤和示例,感兴趣的小伙伴可以了解下... 目录1. 网络数据接收2. 缓冲区管理(处理粘包/拆包)3. 常见数据格式解析3.1 jsON解析3.2 XML解析3.3 自定义