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

相关文章

Java实现检查多个时间段是否有重合

《Java实现检查多个时间段是否有重合》这篇文章主要为大家详细介绍了如何使用Java实现检查多个时间段是否有重合,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录流程概述步骤详解China编程步骤1:定义时间段类步骤2:添加时间段步骤3:检查时间段是否有重合步骤4:输出结果示例代码结语作

使用C++实现链表元素的反转

《使用C++实现链表元素的反转》反转链表是链表操作中一个经典的问题,也是面试中常见的考题,本文将从思路到实现一步步地讲解如何实现链表的反转,帮助初学者理解这一操作,我们将使用C++代码演示具体实现,同... 目录问题定义思路分析代码实现带头节点的链表代码讲解其他实现方式时间和空间复杂度分析总结问题定义给定

Java覆盖第三方jar包中的某一个类的实现方法

《Java覆盖第三方jar包中的某一个类的实现方法》在我们日常的开发中,经常需要使用第三方的jar包,有时候我们会发现第三方的jar包中的某一个类有问题,或者我们需要定制化修改其中的逻辑,那么应该如何... 目录一、需求描述二、示例描述三、操作步骤四、验证结果五、实现原理一、需求描述需求描述如下:需要在

如何使用Java实现请求deepseek

《如何使用Java实现请求deepseek》这篇文章主要为大家详细介绍了如何使用Java实现请求deepseek功能,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录1.deepseek的api创建2.Java实现请求deepseek2.1 pom文件2.2 json转化文件2.2

python使用fastapi实现多语言国际化的操作指南

《python使用fastapi实现多语言国际化的操作指南》本文介绍了使用Python和FastAPI实现多语言国际化的操作指南,包括多语言架构技术栈、翻译管理、前端本地化、语言切换机制以及常见陷阱和... 目录多语言国际化实现指南项目多语言架构技术栈目录结构翻译工作流1. 翻译数据存储2. 翻译生成脚本

如何通过Python实现一个消息队列

《如何通过Python实现一个消息队列》这篇文章主要为大家详细介绍了如何通过Python实现一个简单的消息队列,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录如何通过 python 实现消息队列如何把 http 请求放在队列中执行1. 使用 queue.Queue 和 reque

Python如何实现PDF隐私信息检测

《Python如何实现PDF隐私信息检测》随着越来越多的个人信息以电子形式存储和传输,确保这些信息的安全至关重要,本文将介绍如何使用Python检测PDF文件中的隐私信息,需要的可以参考下... 目录项目背景技术栈代码解析功能说明运行结php果在当今,数据隐私保护变得尤为重要。随着越来越多的个人信息以电子形

使用 sql-research-assistant进行 SQL 数据库研究的实战指南(代码实现演示)

《使用sql-research-assistant进行SQL数据库研究的实战指南(代码实现演示)》本文介绍了sql-research-assistant工具,该工具基于LangChain框架,集... 目录技术背景介绍核心原理解析代码实现演示安装和配置项目集成LangSmith 配置(可选)启动服务应用场景

使用Python快速实现链接转word文档

《使用Python快速实现链接转word文档》这篇文章主要为大家详细介绍了如何使用Python快速实现链接转word文档功能,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 演示代码展示from newspaper import Articlefrom docx import

前端原生js实现拖拽排课效果实例

《前端原生js实现拖拽排课效果实例》:本文主要介绍如何实现一个简单的课程表拖拽功能,通过HTML、CSS和JavaScript的配合,我们实现了课程项的拖拽、放置和显示功能,文中通过实例代码介绍的... 目录1. 效果展示2. 效果分析2.1 关键点2.2 实现方法3. 代码实现3.1 html部分3.2