Skip to content

Multitargeted patches

Geoffrey Horsington edited this page May 28, 2021 · 2 revisions

In some cases you may want to apply the same patch onto multiple methods easily. This is useful for patching similar getters or for quick logging. By default, Harmony does not allow you to mix multiple patch targets via multiple HarmonyPatch attributes -- instead they are all merged into one.

HarmonyX lifts this limitation for method attributes to allow more concise patching syntax with type-level patching.

How does it work?

The functionality relies on the notion of complete HarmonyPatch attributes.
HarmonyPatch attribute is complete, if it defines both target type and target method.

Thus, to use multitargeting:

  • Define one or more complete HarmonyPatch attributes on a method.
  • Define on of patch type attributes: HarmonyPrefix, HarmonyPostfix, HarmonyTranspiler or HarmonyFinalizer. Only one type attribute is allowed.
  • Any incomplete HarmonyPatch attribute will get merged into the last complete attribute.
  • Patch parameters must be compatible with all targets.

Example

// Example target classes
class TargetType1 {
    void SomeMethod1();
}

class TargetType2 {
   void SomeMethod2();
}


// Apply prefix onto both methods at the same time
[HarmonyPrefix]
[HarmonyPatch(typeof(TargetType1), "SomeMethod1")]
[HarmonyPatch(typeof(TargetType2), "SomeMethod2")]
static void SomeMethodPrefix();