FixDestroyImmediatePatcher.cs 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Reflection;
  6. using System.Text;
  7. using Mono.Cecil;
  8. using Mono.Cecil.Cil;
  9. namespace SuppressTransformDestroy.Patcher
  10. {
  11. public static class FixDestroyImmediatePatcher
  12. {
  13. public static string[] TargetAssemblyNames = {"UnityEngine.dll"};
  14. public static void Patch(AssemblyDefinition def)
  15. {
  16. AssemblyDefinition hooksAd;
  17. try
  18. {
  19. hooksAd = AssemblyDefinition.ReadAssembly(Path.Combine(
  20. Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "SuppressTransformDestroy.Managed.dll"));
  21. }
  22. catch (Exception)
  23. {
  24. return;
  25. }
  26. var hooksTd = hooksAd.MainModule.GetType("SuppressTransformDestroy.Managed.DestroyFixer");
  27. var destroyImmediateHook = hooksTd.Methods.FirstOrDefault(m => m.Name == "DestroyCustomImmediate");
  28. var md = def.MainModule;
  29. var objTd = md.GetType("UnityEngine.Object");
  30. var destroyImmediate =
  31. objTd.Methods.FirstOrDefault(m => m.Name == "DestroyImmediate" && m.Parameters.Count == 1);
  32. if (destroyImmediate == null)
  33. return;
  34. var il = destroyImmediate.Body.GetILProcessor();
  35. var ins = destroyImmediate.Body.Instructions[0];
  36. il.InsertBefore(ins, il.Create(OpCodes.Ldarga, destroyImmediate.Parameters[0]));
  37. il.InsertBefore(ins, il.Create(OpCodes.Call, md.ImportReference(destroyImmediateHook)));
  38. }
  39. }
  40. }