Tutorial 4: Patching Methods - rspforhp/WildfrostModdingDocumentation GitHub Wiki

Welcome back! In this tutorial, we will showcase some examples of modifying methods in the base game of Wildfrost.

Background

The modding framework of Wildfrost is done using the Harmony library, which allows for "patching, replacing, and decorating .NET methods during runtime". While a Harmony instance is active (always in our case), method calls can be rerouted to the Harmony instance's modified methods. This is a very powerful tool to use. The Harmony library has its own documentation and several helpful sections about patching: here. This tutorial will not try to cover patching at the level of detail the Harmony docs will. Instead, we show some applicable scenarios to use some of the techniques from the doc alongside helpful explanations.

Prefixes

When Wildfrost v1.2 (June 3rd, 2024) was released, it added several new Steam achievements among other stuff. For the modding branch, which still on v1.1 at the time of writing, this created an interesting issue.



Calling this an issue is an overstatement. You can click "Oh NO!" and the game will continue as if nothing happened. However, this error pops up every time you enter the town, so it can be a bit annoying. The solution: simply stop the CheckAchievement class from running Check(). Surprisingly, the solution is just a two-liner.

[HarmonyPatch(typeof(CheckAchievements), "Start")]
class PatchAchievements { static bool Prefix() => false; }

Let's take this line-by-line. The first line specifies what method you are modifying. In this case, we are modifying the Start method in the class CheckAchievements. If a method is overloaded, you may also specify the argument types in the method signature (see the next example).

The second line has the modifications itself. All modifications are written in the form of a class. In our case, our modification needs to prevent Start from properly running. In the patch class, we create a static method named Prefix, which Harmony recognize as a method to run before running the original method. Our Prefix method returns a bool. A value of true indicates to Harmony to run the original method and other prefixes. A value of false indicates to skip the original method and most other prefixes. Since our Prefix only returns false, CheckAchievements.Start() will never run. Now we move on to an important question?

Where do I put this patch?

Anywhere that does not cause a compile error. As long as these two lines are anywhere reasonable in your assembly, the patch will be found and used whenever your mod is turned on. That said, your assembly still has to be recognized as a mod, so you must do the bare minimum in that regard (make a class that extends WildfrostMod and implement all required fields. See Basic Project Setup).

After you do all of this, you can build the .dll file and run the mod and see (assuming this error has not been fixed yet).

To be continued later...