Chainloader.cs 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. using BepInEx.Common;
  2. using ChaCustom;
  3. using Harmony;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.IO;
  7. using System.Linq;
  8. using System.Reflection;
  9. using System.Text;
  10. using UnityEngine;
  11. namespace BepInEx
  12. {
  13. public class Chainloader
  14. {
  15. static bool loaded = false;
  16. public static List<BaseUnityPlugin> Plugins { get; protected set; } = new List<BaseUnityPlugin>();
  17. public static GameObject ManagerObject { get; protected set; } = new GameObject("BepInEx_Manager");
  18. public static void Initialize()
  19. {
  20. if (loaded)
  21. return;
  22. try
  23. {
  24. UnityEngine.Object.DontDestroyOnLoad(ManagerObject);
  25. if (Directory.Exists(Utility.PluginsDirectory))
  26. {
  27. var pluginTypes = LoadTypes<BaseUnityPlugin>(Utility.PluginsDirectory);
  28. //Log($"{pluginTypes.Count()} plugins found");
  29. foreach (Type t in pluginTypes)
  30. {
  31. var plugin = (BaseUnityPlugin)ManagerObject.AddComponent(t);
  32. Plugins.Add(plugin);
  33. //Log($"Loaded [{plugin.Name}]");
  34. }
  35. }
  36. }
  37. catch (Exception ex)
  38. {
  39. UnityInjector.ConsoleUtil.ConsoleWindow.Attach();
  40. //UnityInjector.ConsoleUtil.ConsoleEncoding.ConsoleCodePage = 932;
  41. Console.WriteLine("Error occurred starting the game");
  42. Console.WriteLine(ex.ToString());
  43. }
  44. loaded = true;
  45. }
  46. public static List<Type> LoadTypes<T>(string directory)
  47. {
  48. List<Type> types = new List<Type>();
  49. Type pluginType = typeof(T);
  50. foreach (string dll in Directory.GetFiles(Path.GetFullPath(directory), "*.dll"))
  51. {
  52. try
  53. {
  54. AssemblyName an = AssemblyName.GetAssemblyName(dll);
  55. Assembly assembly = Assembly.Load(an);
  56. foreach (Type type in assembly.GetTypes())
  57. {
  58. if (type.IsInterface || type.IsAbstract)
  59. {
  60. continue;
  61. }
  62. else
  63. {
  64. if (type.BaseType == pluginType)
  65. types.Add(type);
  66. }
  67. }
  68. }
  69. catch (BadImageFormatException)
  70. {
  71. }
  72. }
  73. return types;
  74. }
  75. }
  76. }