CodeLoader.cs 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  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. private Type[] allTypes;
  16. public CodeMode CodeMode { get; set; }
  17. private CodeLoader()
  18. {
  19. }
  20. public void Dispose()
  21. {
  22. }
  23. public void Start()
  24. {
  25. switch (this.CodeMode)
  26. {
  27. case CodeMode.Mono:
  28. {
  29. Dictionary<string, UnityEngine.Object> dictionary = AssetsBundleHelper.LoadBundle("code.unity3d");
  30. byte[] assBytes = ((TextAsset)dictionary["Code.dll"]).bytes;
  31. byte[] pdbBytes = ((TextAsset)dictionary["Code.pdb"]).bytes;
  32. assembly = Assembly.Load(assBytes, pdbBytes);
  33. this.allTypes = assembly.GetTypes();
  34. IStaticMethod start = new MonoStaticMethod(assembly, "ET.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.Entry", "Start");
  45. start.Run();
  46. break;
  47. }
  48. }
  49. }
  50. // 热重载调用下面三个方法
  51. // CodeLoader.Instance.LoadLogic();
  52. // Game.EventSystem.Add(CodeLoader.Instance.GetTypes());
  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. List<Type> listType = new List<Type>();
  71. listType.AddRange(this.assembly.GetTypes());
  72. listType.AddRange(hotfixAssembly.GetTypes());
  73. this.allTypes = listType.ToArray();
  74. }
  75. public Type[] GetTypes()
  76. {
  77. return this.allTypes;
  78. }
  79. }
  80. }