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

相关文章

基于 HTML5 Canvas 实现图片旋转与下载功能(完整代码展示)

《基于HTML5Canvas实现图片旋转与下载功能(完整代码展示)》本文将深入剖析一段基于HTML5Canvas的代码,该代码实现了图片的旋转(90度和180度)以及旋转后图片的下载... 目录一、引言二、html 结构分析三、css 样式分析四、JavaScript 功能实现一、引言在 Web 开发中,

SpringBoot中使用Flux实现流式返回的方法小结

《SpringBoot中使用Flux实现流式返回的方法小结》文章介绍流式返回(StreamingResponse)在SpringBoot中通过Flux实现,优势包括提升用户体验、降低内存消耗、支持长连... 目录背景流式返回的核心概念与优势1. 提升用户体验2. 降低内存消耗3. 支持长连接与实时通信在Sp

Conda虚拟环境的复制和迁移的四种方法实现

《Conda虚拟环境的复制和迁移的四种方法实现》本文主要介绍了Conda虚拟环境的复制和迁移的四种方法实现,包括requirements.txt,environment.yml,conda-pack,... 目录在本机复制Conda虚拟环境相同操作系统之间复制环境方法一:requirements.txt方法

Spring Boot 实现 IP 限流的原理、实践与利弊解析

《SpringBoot实现IP限流的原理、实践与利弊解析》在SpringBoot中实现IP限流是一种简单而有效的方式来保障系统的稳定性和可用性,本文给大家介绍SpringBoot实现IP限... 目录一、引言二、IP 限流原理2.1 令牌桶算法2.2 漏桶算法三、使用场景3.1 防止恶意攻击3.2 控制资源

springboot下载接口限速功能实现

《springboot下载接口限速功能实现》通过Redis统计并发数动态调整每个用户带宽,核心逻辑为每秒读取并发送限定数据量,防止单用户占用过多资源,确保整体下载均衡且高效,本文给大家介绍spring... 目录 一、整体目标 二、涉及的主要类/方法✅ 三、核心流程图解(简化) 四、关键代码详解1️⃣ 设置

Java Spring ApplicationEvent 代码示例解析

《JavaSpringApplicationEvent代码示例解析》本文解析了Spring事件机制,涵盖核心概念(发布-订阅/观察者模式)、代码实现(事件定义、发布、监听)及高级应用(异步处理、... 目录一、Spring 事件机制核心概念1. 事件驱动架构模型2. 核心组件二、代码示例解析1. 事件定义

Nginx 配置跨域的实现及常见问题解决

《Nginx配置跨域的实现及常见问题解决》本文主要介绍了Nginx配置跨域的实现及常见问题解决,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来... 目录1. 跨域1.1 同源策略1.2 跨域资源共享(CORS)2. Nginx 配置跨域的场景2.1

Python中提取文件名扩展名的多种方法实现

《Python中提取文件名扩展名的多种方法实现》在Python编程中,经常会遇到需要从文件名中提取扩展名的场景,Python提供了多种方法来实现这一功能,不同方法适用于不同的场景和需求,包括os.pa... 目录技术背景实现步骤方法一:使用os.path.splitext方法二:使用pathlib模块方法三

CSS place-items: center解析与用法详解

《CSSplace-items:center解析与用法详解》place-items:center;是一个强大的CSS简写属性,用于同时控制网格(Grid)和弹性盒(Flexbox)... place-items: center; 是一个强大的 css 简写属性,用于同时控制 网格(Grid) 和 弹性盒(F

CSS实现元素撑满剩余空间的五种方法

《CSS实现元素撑满剩余空间的五种方法》在日常开发中,我们经常需要让某个元素占据容器的剩余空间,本文将介绍5种不同的方法来实现这个需求,并分析各种方法的优缺点,感兴趣的朋友一起看看吧... css实现元素撑满剩余空间的5种方法 在日常开发中,我们经常需要让某个元素占据容器的剩余空间。这是一个常见的布局需求