Hotfix.cs 2.1 KB

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