CodeLoader.cs 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Reflection;
  5. using UnityEngine;
  6. namespace ET
  7. {
  8. public class CodeLoader: IDisposable
  9. {
  10. public static CodeLoader Instance = new CodeLoader();
  11. public Action Update;
  12. public Action LateUpdate;
  13. public Action OnApplicationQuit;
  14. private Assembly assembly;
  15. public CodeMode CodeMode { get; set; }
  16. private CodeLoader()
  17. {
  18. }
  19. public void Dispose()
  20. {
  21. }
  22. public void Start()
  23. {
  24. switch (this.CodeMode)
  25. {
  26. case CodeMode.Mono:
  27. {
  28. Dictionary<string, UnityEngine.Object> dictionary = AssetsBundleHelper.LoadBundle("code.unity3d");
  29. byte[] assBytes = ((TextAsset)dictionary["Code.dll"]).bytes;
  30. byte[] pdbBytes = ((TextAsset)dictionary["Code.pdb"]).bytes;
  31. assembly = Assembly.Load(assBytes, pdbBytes);
  32. Game.EventSystem.Add(typeof(Game).Assembly);
  33. Game.EventSystem.Add(this.assembly);
  34. Game.EventSystem.LoadAllAssembliesType();
  35. IStaticMethod start = new MonoStaticMethod(assembly, "ET.Client.Entry", "Start");
  36. start.Run();
  37. break;
  38. }
  39. case CodeMode.Reload:
  40. {
  41. byte[] assBytes = File.ReadAllBytes(Path.Combine(Define.BuildOutputDir, "Data.dll"));
  42. byte[] pdbBytes = File.ReadAllBytes(Path.Combine(Define.BuildOutputDir, "Data.pdb"));
  43. assembly = Assembly.Load(assBytes, pdbBytes);
  44. this.LoadLogic();
  45. IStaticMethod start = new MonoStaticMethod(assembly, "ET.Client.Entry", "Start");
  46. start.Run();
  47. break;
  48. }
  49. }
  50. }
  51. // 热重载调用下面两个方法
  52. // CodeLoader.Instance.LoadLogic();
  53. // Game.EventSystem.Load();
  54. public void LoadLogic()
  55. {
  56. if (this.CodeMode != CodeMode.Reload)
  57. {
  58. throw new Exception("CodeMode != Reload!");
  59. }
  60. // 傻屌Unity在这里搞了个傻逼优化,认为同一个路径的dll,返回的程序集就一样。所以这里每次编译都要随机名字
  61. string[] logicFiles = Directory.GetFiles(Define.BuildOutputDir, "Logic_*.dll");
  62. if (logicFiles.Length != 1)
  63. {
  64. throw new Exception("Logic dll count != 1");
  65. }
  66. string logicName = Path.GetFileNameWithoutExtension(logicFiles[0]);
  67. byte[] assBytes = File.ReadAllBytes(Path.Combine(Define.BuildOutputDir, $"{logicName}.dll"));
  68. byte[] pdbBytes = File.ReadAllBytes(Path.Combine(Define.BuildOutputDir, $"{logicName}.pdb"));
  69. Assembly hotfixAssembly = Assembly.Load(assBytes, pdbBytes);
  70. Game.EventSystem.Add(typeof(Game).Assembly);
  71. Game.EventSystem.Add(this.assembly);
  72. Game.EventSystem.Add(hotfixAssembly);
  73. Game.EventSystem.LoadAllAssembliesType();
  74. }
  75. }
  76. }