Hotfix.cs 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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. #if ILRuntime
  50. Log.Debug($"当前使用的是ILRuntime模式");
  51. this.appDomain = new ILRuntime.Runtime.Enviorment.AppDomain();
  52. GameObject code = (GameObject)Game.Scene.GetComponent<ResourcesComponent>().GetAsset("code.unity3d", "Code");
  53. byte[] assBytes = code.Get<TextAsset>("Hotfix.dll").bytes;
  54. byte[] mdbBytes = code.Get<TextAsset>("Hotfix.pdb").bytes;
  55. using (MemoryStream fs = new MemoryStream(assBytes))
  56. using (MemoryStream p = new MemoryStream(mdbBytes))
  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. GameObject code = (GameObject)Game.Scene.GetComponent<ResourcesComponent>().GetAsset("code.unity3d", "Code");
  64. byte[] assBytes = code.Get<TextAsset>("Hotfix.dll").bytes;
  65. byte[] mdbBytes = code.Get<TextAsset>("Hotfix.mdb").bytes;
  66. this.assembly = Assembly.Load(assBytes, mdbBytes);
  67. Type hotfixInit = this.assembly.GetType("ETHotfix.Init");
  68. this.start = new MonoStaticMethod(hotfixInit, "Start");
  69. #endif
  70. Game.Scene.GetComponent<ResourcesComponent>().UnloadBundle($"code.unity3d");
  71. }
  72. }
  73. }