Repository navigation
Writing code mods
Meitou runs standard Kenshi mods (.mod data, textures, meshes) out of the box. A code mod lets you add C# logic on top: simulation systems, dialogue conditions and effects, combat callbacks, custom equipment slots, mod save data, UI extensions, settings, debug commands, and Harmony patches.
This page walks through creating, packaging, and testing a code mod. For a full list of engine hooks, see Code mod hooks. For making characters act via custom AI goals, jobs, and orders, see AI goals and orders. The engine-level contract is documented in docs/modding.md.
-
Current code-mod API version: 3 (adds the AI goals and orders API). Older builds support API 2, and
v0.16.1-nightly.20261107and earlier support API 1 only. API 1 and 2 mods still load; see Moving from API 1 or 2 if you used removed hooks. - BepInEx is not supported. For RE_Kenshi plugins, see RE_Kenshi compatibility.
-
Create a C# class library targeting
net11.0(standard on all platforms since v0.17.4; usenet10.0only for the legacy macOS build or v0.17.3 and older). -
Reference the game DLLs from your Meitou install folder with
Private="false"so they aren't copied into your mod folder (the game provides them at runtime). You can also use theMeitou.ReferencesNuGet package instead of pointing to a local install (see Code mod hooks).<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>net11.0</TargetFramework> <Nullable>enable</Nullable> <ImplicitUsings>enable</ImplicitUsings> </PropertyGroup> <ItemGroup> <!-- Game assemblies: Meitou.Modding (IMod, ModContext, ...) and Meitou.Game.Ui --> <Reference Include="C:\Games\Meitou\MeitouClient.dll" Private="false" /> <Reference Include="C:\Games\Meitou\Meitou.Simulation.dll" Private="false" /> <Reference Include="C:\Games\Meitou\Meitou.Data.dll" Private="false" /> <Reference Include="C:\Games\Meitou\Meitou.Core.dll" Private="false" /> <Reference Include="C:\Games\Meitou\0Harmony.dll" Private="false" /> </ItemGroup> </Project>
Note: Releases after v0.17.1 no longer ship separate
Meitou.Modding.dllorMeitou.Ui.dllfiles; both are merged intoMeitouClient.dll. Mods built against v0.17.1 or earlier need to be rebuilt. -
Implement
IModas your entry point:using Meitou.Modding; using Meitou.Simulation; namespace MyMod; public sealed class MyMod : IMod { public void Initialize(ModContext c) { c.Log("hello from MyMod"); c.AddSystem("counter", ctx => new CounterSystem(), SystemAnchor.AfterPart(StandardParts.Combat)); } }
-
Place your mod inside the Kenshi
modsfolder alongside a matching.modfile (it can be empty if you don't need FCS data):Kenshi/mods/MyMod/ MyMod.mod meitou.json MyMod.dll -
Add a
meitou.jsonmanifest:{ "id": "mymod", "version": "1.0.0", "apiVersion": 3, "assemblies": ["MyMod.dll"], "entry": "MyMod.MyMod" } -
Enable the mod in the Meitou launcher and click Play. Your log message will show up in
log.txtnext to the game executable.
| Key | Description |
|---|---|
id |
Unique mod identifier: letters, digits, ., _, or -, up to 64 characters. Used for save data, your Harmony instance, and logs. Never change it after release, or players will lose their saved mod data. |
version |
Optional. SemVer version string (e.g. 1.2.0), checked by other mods' version ranges. |
apiVersion |
Target code-mod API version: 1, 2, or 3. If the game doesn't support it, the mod is refused with a clear message. Set this to 3 if you use AI goals and orders. |
assemblies |
Your mod's DLL filenames in load order. Never include the game's own DLLs or dependency DLLs. |
entry |
Full type name of your IMod class. Must have a public parameterless constructor. |
dependencies |
Optional (API 2+). Other code mods your mod depends on, referenced by id. See Depending on another mod. |
loadAfter |
Optional (API 2+). Mod IDs that must load before yours if they happen to be enabled. Affects load order only; they aren't required. |
incompatible |
Optional (API 2+). Mods that cannot run alongside yours. Each entry is an ID string or { "id": "...", "version": "<3.0.0" }. |
gameVersion |
Optional (API 2+). Supported Meitou versions, e.g. ">=0.16.0 <0.17.0". Nightlies match their base release (0.16.1-nightly.x counts as 0.16.1). |
Version ranges are space-separated comparators that must all be satisfied: >=, >, <=, <, or = (a bare version means =). JSON comments and trailing commas are allowed.
- Meitou loads enabled mods in load order. Disabled mod DLLs are never touched. The game never silently reorders your list; the launcher's Arrange button calculates a valid order and previews the moves before applying them.
- If a required dependency is missing, disabled, placed lower in the load order, out of version range, or failed to load, your mod is refused with a clear explanation.
- Every enabled code mod runs automatically. Enabling a code mod counts as consent; there is no separate trust prompt.
- Each mod gets its own isolated assembly load context. Game DLLs and Harmony always resolve from the game itself (even if copies sit in your mod folder), so a mod compiled against a slightly different build still loads; use
gameVersionto restrict releases. Missing members only fail when actually executed. Third-party libraries you bundle load from your own folder, so two mods can safely ship different versions of the same library. -
Initializeruns once on a background thread after game data finishes loading and before any world is created. - If
Initializethrows an exception, your mod is unloaded cleanly: all of its registrations are discarded, its Harmony patches are rolled back, and the game continues normally.
All registrations must happen inside Initialize.
c.AddSystem("counter", ctx => new CounterSystem(), SystemAnchor.AfterPart(StandardParts.Combat));- Your factory runs once per world: every new game and every loaded save creates fresh instances of your systems.
-
SystemAnchor.Before(part),SystemAnchor.AfterPart(part), andSystemAnchor.Endcontrol where your system runs in the simulation tick. If the target part doesn't exist in a scene (for example, test scenes without aggro), your system is placed at the end. - Call
ctx.Find<T>()to access built-in systems, such asctx.Find<Meitou.Simulation.Combat.CombatSystem>(). - Implement only the
ITickSystemphases you need (Inputs,Schedule,Think,Move,BeforeAct,Act,Apply,SlowWorld). Read the determinism rules before implementing any parallel phase. - Implement
IStateHashedso your system's state is included in the world hash checked by the determinism tool.
Implement IModSaveData on your system:
public sealed class CounterSystem : ITickSystem, IStateHashed, IModSaveData
{
int count;
public void SlowWorld(World world) => count++;
public void Hash(ref StateHasher h) => h.Add(count);
public void Write(Stream s) => new BinaryWriter(s).Write(count);
public void Read(Stream s) => count = new BinaryReader(s).ReadInt32();
}Your data is stored in meitou-mods/<your-id>.dat inside the save folder, leaving Kenshi's native save files untouched. Read is only called if the save contains data for that system; otherwise it keeps its initial state. If a player loads and re-saves without your mod enabled, your .dat file is preserved untouched. Importing a save resets mod data.
Mod condition and effect codes start at 1000 (lower numbers are reserved for the base game). Reference your codes in FCS dialogue records as the condition name or action name of a DIALOG_ACTION.
c.AddDialogueCondition(1000, check => check.Matches(IsRaining(check.World)));
c.AddDialogueCondition(1001, check => check.Compare(CountDogs(check.World, check.Subject)));
c.AddDialogueEffect(1000, act => act.World.Post("Something happened"));-
Matches(bool)andCompare(double)evaluate the condition's value and comparison operator just like vanilla conditions. - Conditions must be read-only because the game also evaluates them for UI previews.
- Effects run serially when the dialogue line is spoken.
- To inject custom player replies into conversations, see
AddDialogueRepliesin Code mod hooks. - Only one mod can claim a given code; if two mods claim the same number, the second mod is refused.
c.AddRecordType(5000, "MY_THING");
foreach (var record in c.Records(5000)) { /* ... */ }This reserves the record type number so other mods cannot collide with it. Note that whether custom record types survive full data merges and saves has not been tested yet.
c.AddEquipmentSlot(new ModSlot("mymod_hands", 10, 2, 2, 300, 120)); // section, FCS slot, width, height, x, yModSlot lives in Meitou.Simulation.Items (available after v0.17.5-nightly.20261112.2).
- Creates a new inventory section using the first argument as its name. Any
ARMOURorITEMrecord with a matching FCSslotvalue can be equipped there, so your items remain standard.modrecords (10isATTACH_GLOVES,11isATTACH_NECK). - Allowed
slotnumbers are4,10,11, or15and above (other numbers belong to the base game). Colliding with a built-in section name or another mod's name or slot number refuses your mod. - Each slot holds one item (1 to 20 grid cells wide and tall) and behaves like standard worn gear for armour stats, appearance, equipping, trading, looting, and locks.
- Appears in the character and loot windows styled like the belt slot, positioned at
(x, y)in UI-scale-1 pixels from the window's top-left corner. Choose an empty area since the window won't resize to fit it. Animals do not get custom slots. - Saves store the section name. If the save is loaded without your mod, the equipped item safely returns to the character's main inventory grid.
- Implement
ICombatHitObserveron a registered system to receiveHitResolved(World, in CombatHit)for every landed melee hit, projectile hit, and execution blow (including damage dealt, armour absorbed, body part, attacker, and victim). You can read the world and update your own system state, but any changes to the game world should be queued as commands. Throwing an exception disables the observer for that world. - Use
c.AddCombatHitFeed(hits => ...)for visual effects only (blood, hit markers). It runs once per frame on the render thread with all hits since the previous frame. Never touch the simulation world here, and copy any data you need to keep because the list is reused.
c.AddUi(extension) registers an IUiExtension (from Meitou.Game.Ui in MeitouClient.dll), letting you define custom styles, controls, actions, overrides for vanilla UI, and HUD slot widgets (UiSlots). Inside Register, you can also attach controls to built-in screens, tweak existing widgets, and add right-click menu rows, panel lines, tooltips, dialogue replies, and fallback fonts (see Code mod hooks). Use c.Interface to open built-in screens or control game speed and pause.
public sealed class MySettings
{
[Setting("Dog count", Min = 0, Max = 20)] public int Dogs { get; set; } = 5;
[Setting("Loud dogs")] public bool Loud { get; set; }
}
var group = c.AddSettings(new MySettings());
group.Changed += setting => { /* copy into your system's inputs */ };You can register one settings object per mod. Properties with [Setting] appear under your mod on the Settings screen's Mods tab:
-
bool: toggle switch - numeric types: slider (
MinandMaxrequired, optionalStep) -
enumorstringwithOptions: dropdown list -
stringwithoutOptions: single-line text box (MaxLength, default 256)
Your property initializers act as defaults, and saved player values are loaded before AddSettings returns. Because settings change outside the simulation tick, copy updated values into your simulation during a serial phase.
c.AddDebugCommand("Spawn dogs", d =>
{
d.Enqueue(new MySpawnDogs(d.Target) { Tick = d.Tick });
return "dogs coming";
}, hasField: false);Adds a button (and optional text input if hasField: true) to the F10 debug menu below the built-in entries. Because the handler may run while a tick is in progress, never modify the world directly; read the context, queue a command, and return status text.
Create your own SimCommand record types, queue them via c.Enqueue (or a callback context's Enqueue), and process them in your system's Inputs phase.
One code mod can build on another code mod (such as a shared library or framework) and call its types directly:
"dependencies": [
"rivalry.core",
{ "id": "settlement.visitors", "version": ">=1.2.0 <2.0.0", "optional": true }
]- A plain string defines a required dependency on any version. An object lets you specify
id, aversionrange, andoptional. - Dependencies must sit above your mod in the load order (the launcher's Arrange button handles this) and always initialize before yours.
- Reference the dependency DLL in your
.csprojwithPrivate="false", and do not list it in yourmeitou.jsonassemblies. - If a required dependency fails to load, your mod is refused. If an optional dependency is missing, your mod loads without it.
public void Initialize(ModContext c)
{
var rivalry = c.Dependency<IRivalryApi>("rivalry.core")!; // required: never null
if (c.HasDependency("settlement.visitors")) UseVisitors(c); // optional: check first
}
// Keep optional dependency types in a separate non-inlined method.
// .NET resolves every type referenced inside a method as soon as it JIT-compiles that method.
[MethodImpl(MethodImplOptions.NoInlining)]
static void UseVisitors(ModContext c) => c.Dependency<VisitorsMod>("settlement.visitors")!.AddBuyer(/* ... */);Never reference an optional dependency's types directly inside Initialize, in class fields, or in lambdas created inside Initialize. If the optional mod isn't installed, the JIT compiler will throw a FileNotFoundException when compiling Initialize, causing your mod to be refused.
Building a framework mod: put your public API in a single DLL listed in assemblies, expose an interface that your entry class implements, and bump the major version on breaking changes (so dependents can safely pin >=1.2.0 <2.0.0). If dependents register callbacks or data with you, key them by the caller's c.Id and implement IModDependents to clean them up if a dependent fails to initialize. Also add your .mod to dependents' FCS header dependencies so data files sort properly. See docs/modding-dependencies.md for full details.
Saves record which code mods were active in meitou-mods/environment.json. If you later load the save with a mod removed, updated, or reordered, the game shows a notice and loads the save anyway.
For anything not covered by built-in hooks, use Harmony via c.Harmony (pre-created with your mod's id).
- All mods share the single Harmony instance bundled with the game. Don't ship your own copy; it will be ignored.
- Small methods can be inlined by the JIT, causing patches on them to silently do nothing. Target larger methods or patch their callers instead.
- When code mods are active, the game delays background precompilation until after
Initializefinishes, so patches applied inInitializealways hit fresh methods. - Avoid bundling shared helper DLLs with Harmony patches inside them; if two mods ship the same helper DLL, Harmony can mix up their patches. Keep your patch classes in your own mod assembly.
- Harmony patching on Linux and macOS has not been tested yet.
Meitou's simulation is deterministic: given the same inputs, it produces identical results across machines and thread counts. Keep your systems and patches deterministic:
- During parallel phases (
Think,Move,BeforeAct,Act), only write toNextslots in your own partition, only readPreviousand spatial grids, and send changes targeting other characters throughEffectBuffer. - Never use
System.Randomor system wall-clock time. UseRng.Hash(world.Seed, key, c.RngPurpose, counter)instead. - Never iterate over a
DictionaryorHashSetin ways that affect simulation outcomes without sorting first. - Never modify world state outside a tick. Push external input through
Enqueue.
Meitou ships with meitou-tools next to the game executable. Run it from a terminal in your Meitou folder:
meitou-tools mod-check "<save folder>" --mod "<your mod folder>"
(On Linux and macOS, use ./meitou-tools. It locates Kenshi automatically, or you can set KENSHI_PATH.)
mod-check loads the save with your mod, runs it three times (including single-threaded vs. multi-threaded runs), and compares the world state hash right after loading and after every tick. It prints either PASS or the exact tick, state, and system where runs diverged:
DIFFERS 1 against 4 threads: from tick 152
mod mymod system 'race'
baseline the game alone agrees: the difference comes with the mods
If runs diverge after a tick, mod-check replays up to that tick and pinpoints the first diverging phase, the affected characters, and the differing fields with both values. If runs already differ right after loading, check for leftover state that wasn't reset between worlds (such as static fields or mutated game data).
Test on a busy save with at least 64 characters so threading bugs actually surface. Useful flags: --ticks n (default 600) and --threads n (default 4).
Common reasons a mod is refused (shown in-game and in log.txt):
| Message | How to fix |
|---|---|
bad meitou.json |
Fix the syntax or value error in meitou.json; the message names the offending key. |
built for code-mod API n |
Rebuild your mod against the current Meitou API version. |
uses dependencies, ..., which need apiVersion 2 |
Set apiVersion to 2 (or 3). |
built for Meitou range; this is x |
Your gameVersion range excludes this Meitou build. Update the mod or the game. |
needs X, which is not installed / not enabled |
Install and enable mod X. |
needs X, which loads after it |
Move X above your mod (or click Arrange in the launcher). |
needs X, which is refused: ... |
Fix the error preventing X from loading first. |
needs X range; v is installed |
Install a version of X that matches the required range. |
must load after X |
Move X above your mod (or click Arrange). |
is incompatible with X |
Disable one of the two mods. |
id is taken by mod X |
Another mod loading earlier uses the same id. |
X.dll is missing |
Only list DLLs that actually exist in your mod folder. |
X.dll is one of the game's own assemblies |
Remove the game DLL from assemblies in meitou.json. |
X.dll comes from one of its dependencies |
Remove the framework's DLL from assemblies in meitou.json. |
entry type ... |
Verify entry is the full type name, implements IMod, and has a public parameterless constructor. |
failed to start |
Initialize threw an exception; check log.txt for the stack trace. |
If a mod loads but tries to call a member that was removed in a newer Meitou release (such as an API 1/2 hook replaced in API 3), Meitou doesn't crash or refuse the whole mod. Instead, it stops just the broken part, continues running the game, and displays a single notice for the session:
Mod <mod> was built for another version of the game and needs an update; it is stopped and the rest of the game goes on.
Rebuild the mod against the current Meitou release (see Moving from API 1 or 2).
Code mods execute native .NET code with your user account's permissions, just like any program you install. Meitou cannot sandbox them. Only install and enable code mods from authors you trust.