HookPool.cs 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using System.Reflection;
  4. using UnityEngine;
  5. using System.Linq;
  6. using System.IO;
  7. #if UNITY_EDITOR
  8. using UnityEditor;
  9. #endif
  10. namespace MonoHook
  11. {
  12. /// <summary>
  13. /// Hook 池,防止重复 Hook
  14. /// </summary>
  15. public static class HookPool
  16. {
  17. private static Dictionary<MethodBase, MethodHook> _hooks = new Dictionary<MethodBase, MethodHook>();
  18. public static void AddHook(MethodBase method, MethodHook hook)
  19. {
  20. MethodHook preHook;
  21. if (_hooks.TryGetValue(method, out preHook))
  22. {
  23. preHook.Uninstall();
  24. _hooks[method] = hook;
  25. }
  26. else
  27. _hooks.Add(method, hook);
  28. }
  29. public static MethodHook GetHook(MethodBase method)
  30. {
  31. if (method == null) return null;
  32. MethodHook hook;
  33. if (_hooks.TryGetValue(method, out hook))
  34. return hook;
  35. return null;
  36. }
  37. public static void RemoveHooker(MethodBase method)
  38. {
  39. if (method == null) return;
  40. _hooks.Remove(method);
  41. }
  42. public static void UninstallAll()
  43. {
  44. var list = _hooks.Values.ToList();
  45. foreach (var hook in list)
  46. hook.Uninstall();
  47. _hooks.Clear();
  48. }
  49. public static void UninstallByTag(string tag)
  50. {
  51. var list = _hooks.Values.ToList();
  52. foreach (var hook in list)
  53. {
  54. if(hook.tag == tag)
  55. hook.Uninstall();
  56. }
  57. }
  58. public static List<MethodHook> GetAllHooks()
  59. {
  60. return _hooks.Values.ToList();
  61. }
  62. }
  63. }