CodeLoader.cs 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  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. Dictionary<string, Type> types = AssemblyHelper.GetAssemblyTypes(typeof (Game).Assembly, this.assembly);
  33. Game.EventSystem.Add(types);
  34. IStaticMethod start = new MonoStaticMethod(assembly, "ET.Client.Entry", "Start");
  35. start.Run();
  36. break;
  37. }
  38. case CodeMode.Reload:
  39. {
  40. byte[] assBytes = File.ReadAllBytes(Path.Combine(Define.BuildOutputDir, "Data.dll"));
  41. byte[] pdbBytes = File.ReadAllBytes(Path.Combine(Define.BuildOutputDir, "Data.pdb"));
  42. assembly = Assembly.Load(assBytes, pdbBytes);
  43. this.LoadLogic();
  44. IStaticMethod start = new MonoStaticMethod(assembly, "ET.Client.Entry", "Start");
  45. start.Run();
  46. break;
  47. }
  48. }
  49. }
  50. // 热重载调用下面两个方法
  51. // CodeLoader.Instance.LoadLogic();
  52. // Game.EventSystem.Load();
  53. public void LoadLogic()
  54. {
  55. if (this.CodeMode != CodeMode.Reload)
  56. {
  57. throw new Exception("CodeMode != Reload!");
  58. }
  59. // 傻屌Unity在这里搞了个傻逼优化,认为同一个路径的dll,返回的程序集就一样。所以这里每次编译都要随机名字
  60. string[] logicFiles = Directory.GetFiles(Define.BuildOutputDir, "Logic_*.dll");
  61. if (logicFiles.Length != 1)
  62. {
  63. throw new Exception("Logic dll count != 1");
  64. }
  65. string logicName = Path.GetFileNameWithoutExtension(logicFiles[0]);
  66. byte[] assBytes = File.ReadAllBytes(Path.Combine(Define.BuildOutputDir, $"{logicName}.dll"));
  67. byte[] pdbBytes = File.ReadAllBytes(Path.Combine(Define.BuildOutputDir, $"{logicName}.pdb"));
  68. Assembly hotfixAssembly = Assembly.Load(assBytes, pdbBytes);
  69. Dictionary<string, Type> types = AssemblyHelper.GetAssemblyTypes(typeof (Game).Assembly, this.assembly, hotfixAssembly);
  70. Game.EventSystem.Add(types);
  71. }
  72. }
  73. }