Hotfix.cs 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Reflection;
  6. using UnityEngine;
  7. namespace ETModel
  8. {
  9. public sealed class Hotfix : Object
  10. {
  11. #if ILRuntime
  12. private ILRuntime.Runtime.Enviorment.AppDomain appDomain;
  13. #else
  14. private Assembly assembly;
  15. #endif
  16. private IStaticMethod start;
  17. public Action Update;
  18. public Action LateUpdate;
  19. public Action OnApplicationQuit;
  20. public Hotfix()
  21. {
  22. }
  23. public void GotoHotfix()
  24. {
  25. #if ILRuntime
  26. ILHelper.InitILRuntime(this.appDomain);
  27. #endif
  28. this.start.Run();
  29. }
  30. public List<Type> GetHotfixTypes()
  31. {
  32. #if ILRuntime
  33. if (this.appDomain == null)
  34. {
  35. return new List<Type>();
  36. }
  37. return this.appDomain.LoadedTypes.Values.Select(x => x.ReflectionType).ToList();
  38. #else
  39. if (this.assembly == null)
  40. {
  41. return new List<Type>();
  42. }
  43. return this.assembly.GetTypes().ToList();
  44. #endif
  45. }
  46. public void LoadHotfixAssembly()
  47. {
  48. Game.Scene.GetComponent<ResourcesComponent>().LoadBundle($"code.unity3d");
  49. GameObject code = (GameObject)Game.Scene.GetComponent<ResourcesComponent>().GetAsset("code.unity3d", "Code");
  50. #if ILRuntime
  51. Log.Debug($"当前使用的是ILRuntime模式");
  52. this.appDomain = new ILRuntime.Runtime.Enviorment.AppDomain();
  53. byte[] assBytes = code.Get<TextAsset>("Hotfix.dll").bytes;
  54. byte[] pdbBytes = code.Get<TextAsset>("Hotfix.pdb").bytes;
  55. using (MemoryStream fs = new MemoryStream(assBytes))
  56. using (MemoryStream p = new MemoryStream(pdbBytes))
  57. {
  58. this.appDomain.LoadAssembly(fs, p, new Mono.Cecil.Pdb.PdbReaderProvider());
  59. }
  60. this.start = new ILStaticMethod(this.appDomain, "ETHotfix.Init", "Start", 0);
  61. #else
  62. Log.Debug($"当前使用的是Mono模式");
  63. byte[] assBytes = code.Get<TextAsset>("Hotfix.dll").bytes;
  64. byte[] pdbBytes = code.Get<TextAsset>("Hotfix.pdb").bytes;
  65. this.assembly = Assembly.Load(assBytes, pdbBytes);
  66. Type hotfixInit = this.assembly.GetType("ETHotfix.Init");
  67. this.start = new MonoStaticMethod(hotfixInit, "Start");
  68. #endif
  69. Game.Scene.GetComponent<ResourcesComponent>().UnloadBundle($"code.unity3d");
  70. }
  71. }
  72. }