Transpiler - IL Editor

Harmony Mods ›› Harmony ››
Parent Previous Next

We've covered the Prefix() and Postfix(), which allows us to execute code before and after a target method.


However, if we only want to change the contents of the vanilla method, we can use the Transpiler method.


The Transpiler allows us to read the IL instructions, and make changes to them. This is similar to how SDX-style PatchScripts work, except it's done when the original method is executing, rather than at build time and saved inside the main DLL.


A Transpiler call is targeted the same way as a Prefix and Postfix methods would be, but instead we use the Transpiler:


using DMT;

using Harmony;

using System.Collections.Generic;

using System.Linq;

using System.Reflection;

using System.Reflection.Emit;

using UnityEngine;


[HarmonyPatch(typeof(XUiC_TargetBar))]

[HarmonyPatch("Update")]

public class SphereII_XUiC_TargetBar : IHarmony

{

   public void Start()

   {

       Debug.Log(" Loading Patch: " + GetType().ToString());

       var harmony = HarmonyInstance.Create(GetType().ToString());

       harmony.PatchAll(Assembly.GetExecutingAssembly());

   }


   // Loops around the instructions and removes the return condition.

   static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)

   {

       int startIndex = -1;

       // Grab all the instructions

       var codes = new List<CodeInstruction>(instructions);

       for(int i = 0; i < codes.Count; i++)

       {

         //  Debug.Log(" OpCode: " + codes[i].opcode.ToString());

           if(codes[i].opcode == OpCodes.Ret)

           {

           //    Debug.Log(" Return Detected: " + i);

               startIndex = i;

               break;

           }

       }


       if ( startIndex > -1)

           codes.RemoveAt(startIndex);


       return codes.AsEnumerable();

   }

}







Created with the Personal Edition of HelpNDoc: Easily create Qt Help files