Modding Tutorials/Modifying classes

From RimWorld Wiki
Jump to navigation Jump to search

Modding Tutorials

Changing methods[edit]

Use Harmony.

Adding fields to classes[edit]

You can't. Not even with Harmony. Maybe you want to subclass instead?

Adding methods to classes[edit]

Yes and no. You can create extension methods that are syntactic sugar for calling static methods, but extension methods do not have access to protected or private fields or methods that an actual class method would.

For example, if you wanted to add a method to Pawn which would tell you if that pawn has a specific trait, you could do the following:

using RimWorld;
using Verse;

namespace MyExampleClassExtension
{
    public static class PawnExtensions
    {
        public static bool HasTrait(this Pawn pawn, TraitDef trait)
        {
            return pawn.story.traits.HasTrait(trait);
        }
    }
}

This can then be called like so:

bool isNudist = pawn.HasTrait(TraitDefOf.Nudist)

Note the first argument to HasTrait: `this Pawn Pawn` -- that tells C# that you are defining an extension method on the Pawn class.

Adding fields to Defs[edit]

You can. The game support something called a DefModExtension. If you have a Def, you can get your mod extension from it. This allows you to add any custom field to any def.

Adding behaviour to the Thing class[edit]

If it's a ThingWithComps, you can add a ThingComp instead. Almost all Things are a ThingWithComps. ThingComps can also be used to store whatever data you need.

Adding behaviour to the Hediff class[edit]

HediffWithComps also support comps. HediffComps are different from ThingComps, but their general use is the same.

Using Harmony to override a non-overridden method[edit]

You can't. Harmony can only patch methods which are actually implemented. You can't patch what isn't there.

Alternatives:

  • Patch the base class instead, then check for the instance.
  • Subclass, and then replace it wherever it's created with Harmony.

Patching the base class of a subclass[edit]

Harmony can only patch methods that actually have IL code. What you can do is patch the parent class. Let your patch take the __instance of the parent and pattern match.

if (!(__instance is SubClass))
    return;