Chainloader.cs 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  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 delegate void EntryLoggedEventHandler(string entry, bool show = false);
  19. public static event EntryLoggedEventHandler EntryLogged;
  20. public static void Log(string entry, bool show = false)
  21. {
  22. EntryLogged?.Invoke(entry, show);
  23. }
  24. public static void Initialize()
  25. {
  26. if (loaded)
  27. return;
  28. try
  29. {
  30. UnityEngine.Object.DontDestroyOnLoad(ManagerObject);
  31. if (Directory.Exists(Utility.PluginsDirectory))
  32. {
  33. var pluginTypes = LoadTypes<BaseUnityPlugin>(Utility.PluginsDirectory);
  34. //Log($"{pluginTypes.Count()} plugins found");
  35. foreach (Type t in pluginTypes)
  36. {
  37. var plugin = (BaseUnityPlugin)ManagerObject.AddComponent(t);
  38. Plugins.Add(plugin);
  39. //Log($"Loaded [{plugin.Name}]");
  40. }
  41. }
  42. }
  43. catch (Exception ex)
  44. {
  45. UnityInjector.ConsoleUtil.ConsoleWindow.Attach();
  46. //UnityInjector.ConsoleUtil.ConsoleEncoding.ConsoleCodePage = 932;
  47. Console.WriteLine("Error occurred starting the game");
  48. Console.WriteLine(ex.ToString());
  49. }
  50. loaded = true;
  51. }
  52. public static List<Type> LoadTypes<T>(string directory)
  53. {
  54. List<Type> types = new List<Type>();
  55. Type pluginType = typeof(T);
  56. foreach (string dll in Directory.GetFiles(Path.GetFullPath(directory), "*.dll"))
  57. {
  58. try
  59. {
  60. AssemblyName an = AssemblyName.GetAssemblyName(dll);
  61. Assembly assembly = Assembly.Load(an);
  62. foreach (Type type in assembly.GetTypes())
  63. {
  64. if (type.IsInterface || type.IsAbstract)
  65. {
  66. continue;
  67. }
  68. else
  69. {
  70. if (type.BaseType == pluginType)
  71. types.Add(type);
  72. }
  73. }
  74. }
  75. catch (BadImageFormatException)
  76. {
  77. }
  78. }
  79. return types;
  80. }
  81. }
  82. }