nyuuzyou/wikis huggingface dataset:
Modding Tutorials/Compatibility with DLLs

==Requirements==
* A mod. Yours, preferably.
* Another mod. Does not have to be yours. May or may not have to be loaded.
* Harmony.
* Hello World.
* The willingness to create compatibility between the two mods.
==Welcome to the Cargo Cult==
Assumptions: 
# You will do manual patching. I do not know of a way to do this with annotation patching.
# You have a class named HarmonyPatches where a static method called PatchOnSomeMethodFromSomeOtherMod_PostFix lives. You can of course change this.
# The name of the mod you want to patch is OtherMod. Darn that OtherMod for messing with your mod! Note that this is the exact name as OtherMod has in its About.xml file.
This snippet was handed down to me from erdelf, who got it from Zhentar, who got it from.. well the exact chain of custody has been lost to the mists of time but you get the idea.
try
{
 ((Action)(() =>
 {
 if (LoadedModManager.RunningModsListForReading.Any(x=> x.Name == "OtherMod"))
 {
 harmony.Patch(AccessTools.Method(typeof(FullNameSpaceOfSomeOtherMod.SomeClass), nameof(FullNameSpaceOfSomeOtherMod.SomeClass.SomeOtherMethod)),
 postfix: new HarmonyMethod(typeof(HarmonyPatches), nameof(PatchOnSomeMethodFromSomeOtherMod_PostFix)));
 }
 }))();
}
catch (TypeLoadException ex) { }
===Disbanding the Cargo Cult===
Okay so the thing that makes Cargo Cult programming bad is that people copy stuff without knowing what it does. So here's what it does, why this terrible looking snippet is sometimes required, and why it works the way it works.
If you know some C#: You're looking at an anonymous delegate cast to an invoked Action inside a try/catch block designed to discard a TypeLoadException. Obviously.
The real question is why? which this article will try its best to answer. Consider this:
The constraints
# The player may or may not have SomeOtherMod activated.
# The player might not even be subscribed to SomeOtherMod.
# We cannot add 'using FullNameSpaceOfSomeOtherMod', as that would create a direct dependency to a potentially non-existing mod (non-existing as far as RimWorld cares anyway).
# Compilers are magic and can look in the future, beyond simple if-statements.
# Compilers love to optimise and in-line.
# The JIT compiler may behave differently per configuration.
# No-Inline is merely a suggestion the compiler may or may not heed.
So what you end up with is a bunch of hoops to jump through to avoid all that, in the form of an anonymous delegate cast to an invoked Action that still requires a try/catch block designed to discard a TypeLoadException.
===Gotchas===
Oh, you thought this was over? If you added OtherMod.dll as a reference and compiled against it, you compiled against the specific AssemblyVersion of that dll. If they update, your patch will break again. Tell them to bump the FileVersion instead (also known as AssemblyFileVersion). Better yet, don't touch it at all. AssemblyVersion is for API breaking changes.
Category:Modding tutorials
Modding Tutorials/Custom Comp Classes

Creating a custom comp class is a convenient way to add new functionality to RimWorld. Comps aren't a formal concept in the code: they're a design pattern used in different places. They allow for a more modular approach to adding functionality to different objects.
=The types of Components=
These are the places where the Comps design pattern is used, each with differing behaviour suited for their respective area. From most specific to most generic:
==HediffComp==
A relatively simple Comp for adding more complex behaviour to Hediffs.
==ThingComp==
A very powerful Component that is tied to a specific Thing. These are often used to store data, give special functionality to the Thing they're tied to and are one of the building blocks of RimWorld modding and RimWorld in general. While not as powerful as a fully custom class, they provide plenty of functionality for a lot of general use cases without compatibility issues.
==WorldObjectComp==
Like a ThingComp, but for WorldObjects.
==MapComponent==
Much like a ThingComp, except these exist at the Map level. They're most useful for keeping tracks of multiple things at once, storing data, and can serve as a coordinator or general managing entity.
==WorldComponent==
Similar to a MapComponent, but lives on the World level.
==GameComponent==
Similar to a WorldComponent, but lives at the Game level.
The distinction between a GameComponent and a WorldComponent might not be too obvious, but a GameComponent gets instantiated when a new Game is started:
* Upon start of the tutorial
* When the player starts the Scenario Configuration (rolling for colonists)
* When a save is loaded from the main menu
==StorytellerComp==
These are a specific type of Component that determines the behaviour of the storyteller.
=Which one to use=
Use whatever is most appropriate, really. Does it deal with a Pawn's health? HediffComp. Is it functionality at Thing level? ThingComp. Does it have to do with two pawns, or multiple items on a map? Probably a MapComponent, or maybe a WorldComponent.
Category:Modding tutorialsCategory:Modding
Modding Tutorials/DebugActions

===Preamble===
Who this is for: Modders that have C# and want to directly call any method
===Example===
The whole idea with a DebugAction is to easily call a method without having to wait or build an elaborate scenario first. 
Debug actions are only available while in Development Mode and the available options are shown by pressing the first cog button in the debug row
// todo image
Any static method can be used to make a debug action, you simply need to add the DebugAction attribute like this
[DebugAction("Showcase", "Spawn Potatoes", actionType = DebugActionType.ToolMapForPawns, allowedGameStates = AllowedGameStates.PlayingOnMap)]
public static void MyDebugAction(Pawn p)
{
 SomeStaticUtility.SpawnPotatoesOnPawn(p);
}
The first argument is the "category" of the DebugAction, you can use this to nicely bundle all your logically connected actions and organize the large amount of buttons on the UI.
The second argument is the label of the button
The third argument is the actionType, which determines how the debug action is used, possible values are:
====Action====
Directly calls the method, can be used in any game state
====ToolMap====
Spawns a mouse targeter that calls the method with each click. can only used if the player is currently on a Map
====ToolMapForPawns====
Spawns a mouse targeter that calls the method with each click on a pawn. Passes the clicked-on pawn to the method as Pawn p. Can only be used if the player is currently on a Map
====ToolWorld====
Spawns a mouse targeter that calls the method with each click on a world tile. Can only be used if the player is currently on the WorldMap (where the hexagonal tiles are)
The fourth argument is the allowedGameStates, which is a (combinable) enum of which game states the debug tool should be visible in the debug action UI
 public enum AllowedGameStates
 {
 Invalid = 0, // never
 Entry = 1, // while the player is on the main menu
 Playing = 2, // after game launch
 WorldRenderedNow = 4, // after a save files world is loaded
 IsCurrentlyOnMap = 8, // while a map is entered
 HasGameCondition = 16, // while a map is entered and a game condition exists (e.g. solar flare)
 PlayingOnMap = 10, // Playing && IsCurrentlyOnMap
 PlayingOnWorld = 6 // Playing && WorldRenderedNow
 }
===Notes===
If you have a decompiler, just searching for any Type with "DebugActions" will yield many results that you can investigate and copy for your own needs.
Category:Modding tutorials
Modding Tutorials/DefModExtension

A DefModExtension is a way to add fields to Defs. DefModExtensions are a simple way to extend functionality to a Def. A DefModExtension doesn't directly add fields to classes as that's technically impossible to do at runtime. The implementation is that the Def class has a public List<DefModExtension> which can easily be extended.
Benefits:
+ Is really simple and light-weight to use.
+ Works on any Def.
+ Exposes its functionality to XML.
+ Compatible with savefiles, other mods, you name it.</br>
+ Does not come with the compatibility issues and pitfalls of creating a custom Def class.
+ Does not have the overhead of a ThingComp.
+ More broadly applicable than a ThingComp (not every Def is a ThingWithComps!).
Downsides:
- Static and global data.
- Can't save data.
- Only works on Defs.
- A DefModExtension does not know what Def it belongs to. (There are ways around this, like setting a Def field in your DefModExtension and populating it in XML/C#)
=Requirements=
You know the deal by now.
* Solution
* Custom code
* C#
* XML
=The Code=
using Verse;
namespace ExampleNameSpace
{
 public class ExampleModExtension : DefModExtension
 {
 public bool canBeARimQuest = true;
 }
}
That's it. DefModExtensions can of course contain any field you wish: a C# Type, a Thingfilter, a list -- but for the sake of a simple example, we'll use a bool.
==Using the DefModExtension==
You can use the DefModExtension on any Def with that extension. Their usage is much the same way as any other field in a Def. The biggest difference is in the syntax; instead of bool value = def.field, it's bool value = def.GetModExtension<ExampleModExtension>().field
using Verse;
using RimWorld;
namespace ExampleNameSpace
{
 public class OurExampleClass
 {
 private static bool IsAcceptableQuest(IncidentDef incidentDef)
 {
 if (incidentDef.letterDef == LetterDefOf.NegativeEvent)
 return false;
 if (incidentDef.HasModExtension<ExampleModExtension>())
 return incidentDef.GetModExtension<ExampleModExtension>().canBeARimQuest;
 return true;
 }
 }
}
Or if you like your code shorter, you can use null conditionals and null coalescing:
 return incidentDef.letterDef != LetterDefOf.NegativeEvent
 && (incidentDef.GetModExtension<ExampleModExtension>()?.canBeARimQuest ?? true); 
 //will return value of mod extension if not null, otherwise assumed true.
==Adding it to your def==
<Defs>
 <ExampleDef>
 <defName>Example</defName>
 <modExtensions>
 
 <canBeARimQuest>false</canBeARimQuest>
 
 </modExtensions>
 </ExampleDef>
</Defs>
===Using xpath to add it to a def===
If you wanted to xpath patch a mod extension onto an existing def, you'd use PatchOperationAddModExtension, which is like PatchOperationAdd but saves having to check if modExtensions has already been added/having to include it in your value field:
<Patch>
 <Operation Class="PatchOperationAddModExtension">
 <xpath>Defs/ExampleDef[defName="Example"]</xpath>
 <value>
 
 <canBeARimQuest>false</canBeARimQuest>
 
 </value>
 </Operation>
</Patch>
=See also=
Ludeon thread on Mod Extensions
The pull request on which the code in this article is based on
Category: Modding
Category: Modding tutorials
Modding Tutorials/Defs

XML Definitions (or just "Defs") are used to add new content to RimWorld. This includes weapons, apparel, equipment, animals, mechs, plants, and many other things.
==Folder Location==
Defs are placed in XML files in the Defs folder of the standard mod folder structure. The exact paths and file names do not matter except for LoadFolders loading within your own mod; you can name and organize your files however you want for your own organization.
You can also find vanilla's Defs in [your Steam folder]\common\RimWorld\Data. You can and should reference vanilla Defs as templates and examples when creating your own. Loading the Data folder into the code editor or IDE workspace of your choice for faster searching is also strongly recommended.
==XML Tutorials==
The following are step-by-step tutorials for creating basic content mods.
Basic Tutorials:
* Basic Melee Weapon - How to create a basic melee weapon with a texture mask
* Basic Ranged Weapon - How to create a basic ranged weapon with custom sound effects
* Basic Plant - How to create a custom plant with both a cultivated and wild variant
* Custom Animal (Upcoming)
* Simple Building (Upcoming)
* Custom Workbench (Upcoming)
* Custom Drug (Upcoming)
Advanced Tutorials:
* Custom Faction (Upcoming)
* Custom Culture (Upcoming)
* Custom Trader Type (Upcoming)
==Creating Custom Defs==
(Placeholder)
==Referencing Defs from C#==
(Placeholder)
Category:Modding
Category:Modding tutorials
Modding Tutorials/First Steps

----
Roaring to go? Here's a good tutorial that introduces a lot of things gradually. Want to take it slow? Smart. It's strongly recommended to do the following before you start making a mod:
= Step 1: Search for a mod already doing what you want =
Seriously. There are so many mods, there is generally one, probably of high quality, doing what you want it to. You might not need to make a mod!
* Search Steam's Workshop. These have ready to go and managed by Steam mods. Click to use them.
* Check the RimWorld Mod Forum
* Use Google because it works.
* Ask on Discord or reddit to see if they know of one.
= Step 2: Read Other Info On Modding =
* RimWorld Wiki - Modding 
* RimWorld Wiki - Modding Tutorials
* RimWorld Forum - Modding Help
* Tynan's Readme.txt in your Rimworld directory (in RimWorldMac.app for Mac people)
= Step 3: One Time Reads =
* RimWorld Wiki - XML file structure and loading
* RimWorld Wiki - Testing 
* A17 Modding Updates - https://ludeon.com/forums/index.php?topic=32735.0 - by ZorbaTHut
= Step 4: Useful Links, Reference Constantly =
* Wiki - Folder Structure
* Ludeon Forum - Modding Help
* RimWorld XML Database - xml explained for XML modders 
= Step 5: Tutorials by Others =
* How to make a .dll-mod (Power Generation) - https://ludeon.com/forums/index.php?topic=3408.0
= Step 6: Reference the works of others =
It's how most of us learned how2mod.
* Core. If it's (close to) something that already exists in RimWorld, use what RimWorld provides you. What better source of "how to do X" than the game itself?
* Maybe there's some inspiration on this list of modders and their GitHub links
* Use GitHub search to find how other modders handled a problem
* Use Google because it works.
Category: Modding tutorials
Category: Modding
Modding Tutorials/Flooring

In this tutorial, we're going to be learning how to add your own flooring to the game using the resource which we created in the last tutorial.
==Prerequisites==
You have completed the Items Tutorial.
You should have read the Getting Started tutorial, which gets you up to speed with how mods are structured in RimWorld. You should also have a good understanding of where files are located (such as About.xml, def XML files, where you should put textures, and so on).
You should also have a look at the TerrainDef article, which should clear up any concerns you have on the attributes we'll be using below.
== Making the folders ==
After you have made your mod folder from the Getting Started tutorial, you will need to create a new folder in which will contain your new flooring xml. Inside your Defs folder create a new subfolder called TerrainDefs. You're now done as far as creating folders go.
== Creating the new flooring (Titanium example) ==
In this example, we'll be making a new titanium flooring using the titanium resource which we created in the last tutorial! Your file should now look like this (if you're making a titanium flooring like me) :
<?xml version="1.0" encoding="utf-8" ?>
<TerrainDefs>
	<TerrainDef>
		<defName>TitaniumFloor</defName>
		<Label>Titanium Flooring</Label>
		<RenderPrecedence>210</RenderPrecedence>
		<Description>A lovely</Description>
		<TexturePath>Things/Buildings/Floors/WoodFlooring</TexturePath>
		<Beauty>NiceTiny</Beauty>
		<SurfacesSupported>
			Light
			Heavy
			SmoothHard
		</SurfacesSupported>
		<WorkToBuild>50</WorkToBuild>
		<DesignationCategory>Structure</DesignationCategory>
		<Fertility>0</Fertility>
		<CostList>
			
				<thingDef>Titanium</thingDef>
				<count>2</count>
			
		</CostList>
		<ConstructionEffect>ConstructDig</ConstructionEffect>
		<AcceptTerrainSourceFilth>True</AcceptTerrainSourceFilth>
	</TerrainDef>
</TerrainDefs>
To find out what each line does and there options, have a look at TerrainDef. There you can also find more lines.
== Testing ==
Let’s test our new mod! Fire up RimWorld, making sure to turn on Development mode in the options menu. Open the mods menu and make sure your mod is ticked (For active), and then press the tilde key (~) to check for any errors thrown on runtime. That’s right, no errors! Enjoy your new flooring!
==Download==
The latest working package of this tutorial can be found here (download).
== Conclusion ==
You now know how to: 
* make a simple flooring
* know most of the TerrainDef's global attributes and their functions with the optional choices
Modding Tutorials/Marked for Deletion

!
 
 
 Marked for Deletion
 This tutorial or guide is not up to the new standards of the RimWorld Wiki tutorial team and has been marked for deletion pending release of newer content that covers the same topic. Please be aware that this page may contain inaccuracies or errors; if you are the author of this page and have questions about this process, please contact us on the #mod-development channel of the RimWorld Discord.
 
 
Category:Notice templates
Modding Tutorials/Modifying classes

=Changing methods=
Use Harmony.
=Adding fields or methods to classes=
You can't. Not even with Harmony. Maybe you want to subclass instead?
=Adding fields to Defs=
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=
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=
HediffWithComps also support comps. HediffComps are different from ThingComps, but their general use is the same.
=Using Harmony to override a non-overridden method=
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=
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;
Category:Modding tutorialsCategory:Modding
Modding Tutorials/Overhaul workspace

NOTE: This is a workspace for the ongoing overhaul of the RimWorld Wiki's modding tutorials and references. If you managed to find your way here, please check out the main modding tutorials index page instead.
This overhaul is being overseen by the #mod-development channel on the RimWorld Discord, please contact us before changing anything.
== Modding Basics ==
Modding Basics
* Getting Started
* Recommended Software
* Mod Folder Structure
* About.xml
* Textures
* Sounds
* Localization
XML
* Defs
* ThingDef
* MayRequire
* PatchOperations
C#
* C# Basics
* Decompiling Source Code - Reading compiled code from the base game as well as DLCs and other mods.
* Setting up - (Needs cleanup)
* Harmony Primer
Code References
* Infrastructure Overview
* Application Startup
* Simulation Lifecycle
* Rendering Lifecycle
* Buildings
* Pawns
* Audio
== Tutorials ==
This will be a curated subset of tutorials that will be vetted, reviewed, and maintained by the overhaul team. These are meant to be a cohesive set of tutorials that guides the reader from the simplest single-Def items such as weapons to building a full custom faction.
=== Basic Tutorials (XML) ===
* Creating a custom melee weapon
* Creating a custom ranged weapon
* Creating a custom plant
* Creating a custom animal
* Creating a simple building
* Creating a custom workbench
* Creating a custom drug
=== Advanced Tutorials (XML) ===
* Creating a custom faction
* Creating a custom culture
* Creating a custom trader type
=== Basic Tutorials (C#) ===
* Creating a custom consumable
=== Advanced Tutorials (C#) ===
* Creating custom texture overlays
Category:Modding tutorials
Modding Tutorials/Transpiler Hints

Debugging Transpilers can seem impossible. It's very difficult to count exactly correctly, and any mistakes will likely throw a system exception.
==Helpful examples==
One way to get an idea of how to use the Transpiler is to search github for Harmony Transpilers.
==Useful debugging tools.==
===See what your IL code is===
One thing that can potentially help is to print out your entire modified IL code, to make sure you've got it correct:
 public static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions, ILGenerator generator) {
 var l=XTranspiler(instructions, generator).ToList(); // name your actual transpiler XTranspiler
 string s="Code:";
 int i=0;
 foreach (var c in l) {
 if (c.opcode==OpCodes.Call ||
 c.opcode==OpCodes.Callvirt) { // you can make certain operations more visible
 Log.Warning(""+i+": "+c);
 } else {
 Log.Message(""+i+": "+c);
 }
 s+="\n"+i+": "+c;
 i++;
 yield return c;
 }
 Log.Error(s); // or just print the entire thing out to copy to a text editor.
 }
Category:Modding tutorials
Modding Tutorials/Troubleshooting/Finding Exceptions

== Preamble: ==
Who this is for: Modders trying to chase down the exact cause of an exception
This approach can be used to track down any type of exception, but the one you are most likely to encounter in RW modding will be a NRE (NullReferenceException), meaning some code is trying to access a member of a NULL instance, this tutorial will elaborate on this exact scenario.
=== What you need: ===
# An exception
# A decompiler of your choice
=== Example ===
This example adds a debug action for my convenience to call another method and an actual static method that spawns potatoes on the same cell as the pawn is standing on
using RimWorld;
using Verse;
namespace ExceptionShowcase
{
 public static class ExceptionShowcase
 {
 /// <summary>
 /// This is a debug action, it shows up in the debug actions menu of your game. This specific one is a ToolMapForPawns, which means the method is passed the Pawn p that was targeted by the user
 /// You don't need this, it's just an easy way for me to make this showcase execute a method on-demand
 /// </summary>
 /// <param name="p">The automatically assigned pawn that you select with the mouse</param>
 [DebugAction("Showcase", "Spawn Potatoes", actionType = DebugActionType.ToolMapForPawns, allowedGameStates = AllowedGameStates.PlayingOnMap)]
 public static void MyDebugAction(Pawn p)
 {
 SpawnPotatoesOnPawn(p);
 }
 /// <summary>
 /// This is the actual method that we are working on
 /// </summary>
 /// <param name="pawn">The pawn to spawn potatoes on</param>
 public static void SpawnPotatoesOnPawn(Pawn pawn)
 {
 // only spawn the potatoes if the pawn can eat them
 bool willEat = FoodUtility.WillEat(pawn, ThingDefOf.RawPotatoes);
 if(!willEat)
 {
 // if the pawn would not eat the potatoes, don't spawn them and just exit the method
 return;
 }
 // get the position and map of the pawn
 IntVec3 position = pawn.Position;
 Map map = pawn.Map;
 // GenSpawn will make a new item of the def and put it on the map and position that we specify
 GenSpawn.Spawn(ThingDefOf.RawPotatoes, position, map);
 }
 }
}
It executes as expected, I am presented with a DebugAction in the menu, it spawns a Targeter, I select a pawn and it spawns potatoes on that pawns position.
Category:Modding tutorials