CodeLoader.cs 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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: Singleton<CodeLoader>
  9. {
  10. private Assembly assembly;
  11. public void Start()
  12. {
  13. if (Define.EnableCodes)
  14. {
  15. Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
  16. Dictionary<string, Type> types = AssemblyHelper.GetAssemblyTypes(assemblies);
  17. EventSystem.Instance.Add(types);
  18. foreach (Assembly ass in assemblies)
  19. {
  20. string name = ass.GetName().Name;
  21. if (name == "Unity.Model.Codes")
  22. {
  23. this.assembly = ass;
  24. }
  25. }
  26. IStaticMethod start = new StaticMethod(assembly, "ET.Entry", "Start");
  27. start.Run();
  28. }
  29. else
  30. {
  31. byte[] assBytes;
  32. byte[] pdbBytes;
  33. if (!Define.IsEditor)
  34. {
  35. Dictionary<string, UnityEngine.Object> dictionary = AssetsBundleHelper.LoadBundle("code.unity3d");
  36. assBytes = ((TextAsset)dictionary["Model.dll"]).bytes;
  37. pdbBytes = ((TextAsset)dictionary["Model.pdb"]).bytes;
  38. }
  39. else
  40. {
  41. assBytes = File.ReadAllBytes(Path.Combine(Define.BuildOutputDir, "Model.dll"));
  42. pdbBytes = File.ReadAllBytes(Path.Combine(Define.BuildOutputDir, "Model.pdb"));
  43. }
  44. assembly = Assembly.Load(assBytes, pdbBytes);
  45. this.LoadHotfix();
  46. IStaticMethod start = new StaticMethod(assembly, "ET.Entry", "Start");
  47. start.Run();
  48. }
  49. }
  50. // 热重载调用该方法
  51. public void LoadHotfix()
  52. {
  53. byte[] assBytes;
  54. byte[] pdbBytes;
  55. if (!Define.IsEditor)
  56. {
  57. Dictionary<string, UnityEngine.Object> dictionary = AssetsBundleHelper.LoadBundle("code.unity3d");
  58. assBytes = ((TextAsset)dictionary["Hotfix.dll"]).bytes;
  59. pdbBytes = ((TextAsset)dictionary["Hotfix.pdb"]).bytes;
  60. }
  61. else
  62. {
  63. // 傻屌Unity在这里搞了个傻逼优化,认为同一个路径的dll,返回的程序集就一样。所以这里每次编译都要随机名字
  64. string[] logicFiles = Directory.GetFiles(Define.BuildOutputDir, "Hotfix_*.dll");
  65. if (logicFiles.Length != 1)
  66. {
  67. throw new Exception("Logic dll count != 1");
  68. }
  69. string logicName = Path.GetFileNameWithoutExtension(logicFiles[0]);
  70. assBytes = File.ReadAllBytes(Path.Combine(Define.BuildOutputDir, $"{logicName}.dll"));
  71. pdbBytes = File.ReadAllBytes(Path.Combine(Define.BuildOutputDir, $"{logicName}.pdb"));
  72. }
  73. Assembly hotfixAssembly = Assembly.Load(assBytes, pdbBytes);
  74. Dictionary<string, Type> types = AssemblyHelper.GetAssemblyTypes(typeof (Game).Assembly, this.assembly, hotfixAssembly);
  75. EventSystem.Instance.Add(types);
  76. }
  77. }
  78. }