Modding:Harmony

From Caves of Qud Wiki
Revision as of 06:51, 25 March 2021 by 87.115.128.78 (talk) (Added details on when to avoid Harmony Patches)
Jump to navigation Jump to search
This article is a stub. You can help Caves of Qud Wiki by expanding it.
This article is a stub. You can help Caves of Qud Wiki by expanding it.

For best results, it's recommended to have read the following topics before this one:

Harmony is a library for dynamically patching C# code. In the context of Caves of Qud modding, it's useful for changing the behavior of things that are not explicitly exposed through the game's modding interface. Harmony is included in the base game, and as such doesn't require any external mods to use.

For a primer on using Harmony to patch game methods, see this article.

While Harmony Patches are powerful and are often the easiest and most obvious way to modify behaviour, they are very prone to buggy behaviour and incompatibility with other mods and future updates. Many things that seem like they can be done with a Harmony Patch at first glance would actually be better achieved by creating a new Part with the desired behaviour and adding it to the required objects - or a similar solution.

That said, there do remain some situations in which harmony patches are required in order to affect certain functionality. In these cases, Postfix Patches tend to be the most compatibility friendly, followed by non-blocking Prefix Patches. Prefix Patches that prevent the main function from running or Transpiler Patches that modify the IL Code of a function are often problematic and should be avoided unless they are the only option.

Example: Chaotic-Colored Message Text

Chaotic-colored message text created by the example harmony patch.

Create somefile.cs in your .../Mods/ModName/ directory, with the following code:

using HarmonyLib;

namespace YourMod.HarmonyPatches
{
    [HarmonyPatch(typeof(XRL.Messages.MessageQueue))]
    class YourPatch1
    {
        [HarmonyPrefix]
        [HarmonyPatch("Add")]
        static void Prefix(ref string Message)
        {
            Message = "{{chaotic|" + Message + "}}";
        }
    }
}