Gids voor modmakers
Making Sons of the Forest mods: the complete guide
Werken met een AI-assistent
Plak deze prompt in ChatGPT, Claude, Cursor of een andere codeerassistent. De AI leest dan deze gids als Markdown en de volledige referentie, en volgt dezelfde regels als jij.
I want to make a Sons of the Forest mod with RedLoader and SonsSdk.
Before writing any code, read this guide and follow it: https://sotf-mods.com/create.md
For deeper details (game API cookbook, Il2Cpp rules, multiplayer, templates) use https://github.com/ChoqueCastroLD/sotf-mods-skill (start with SKILL.md).
Site map for AI tools: https://sotf-mods.com/llms.txt
Rules: never call a game API you have not seen in the interop dumps or the running game, keep the mod working in multiplayer (host-authoritative), and tell me how to test each step in game.
Answer in my language and walk me through it step by step.
My mod idea: [describe what your mod should do] This guide takes you from nothing installed to a polished, multiplayer-ready mod that players download from SOTF Mods, and then shows you how to keep it working. Read it in order the first time; later, jump to the part you need.
You should be able to read basic C#. You don't need to know Unity internals, reverse engineering or networking: the guide explains each of them when you first need it.
Everything here was checked against RedLoader 0.8.6 and the current Steam build of the game. The deeper, more technical version of each part lives in the sotf-mods-skill repository, linked at the end of each section.
The short version, if you want to see the whole path first:
- Install the game, RedLoader and the .NET SDK.
- Create a project from the template and build your first mod. It takes about ten minutes.
- Find the game classes you need with dnSpyEx and UnityExplorer, and hook them with Harmony.
- Make it work in multiplayer and test it in a real session.
- Package the zip and publish it on SOTF Mods.
How Sons of the Forest modding works#
Sons of the Forest is a Unity game built with IL2CPP: the developers' C# code was converted to C++ and compiled to native machine code (GameAssembly.dll). That has two consequences you will feel all the time:
- There is no game C# code to read. You can see the names of classes, fields and methods, but not what the methods do.
- Your C# code can't talk to native code directly. It goes through interop wrappers: generated C# classes with the same names as the game's classes, whose methods forward each call into the native game.
Four pieces make modding possible:
| Piece | What it is |
|---|---|
| RedLoader | The mod loader, a fork of MelonLoader. It is injected into the game when it starts, generates the interop wrappers for the game's code, and loads your mod. |
| SonsSdk | RedLoader's SDK for this game. It gives you a mod base class (SonsMod), lifecycle events and helpers for items, saves, settings, UI, sounds, blueprints and networking. |
| HarmonyX | A library that hooks game methods, so your code runs before or after them, or replaces them. It ships with RedLoader. |
| Photon Bolt | The game's multiplayer library. Multiplayer mods use it through SonsSdk's packet helpers. |
your mod (a C# .dll in Mods/)
| calls classes such as LocalPlayer, ItemDatabaseManager
v
interop wrappers (_RedLoader/Game/*.dll, generated on your PC)
| forward every call
v
the native game (GameAssembly.dll)
SonsSdk: ready-made helpers on top of the wrappers
HarmonyX: hooks that run your code when the game calls one of its methods
The platform is stable: the game's last content patch was on 15 January 2025, and RedLoader 0.8.6 (February 2025) is the last release. What you learn and build today keeps working unless one of them updates (see After release).
Set up your PC#
The game#
Install Sons of the Forest from Steam. The default folder is:
C:\Program Files (x86)\Steam\steamapps\common\Sons Of The Forest
This guide calls it <GameDir>. If you installed the game elsewhere, use your path wherever you see <GameDir>.
RedLoader#
- Download
Redloader.zipfrom the RedLoader releases. - Extract it into
<GameDir>. You now have a_Redloaderfolder,version.dllanddoorstop_config.ininext to the game's exe. - Start the game. The first start generates the interop wrappers (235 dlls) and takes a few minutes. If it takes much longer (around 9 minutes), Windows Defender is scanning every generated dll: add a Defender exclusion for
<GameDir>. - On the title screen you should now see a MODS button. That means RedLoader is working.
The RedManager installer, linked from the RedLoader docs, does the same and can also install extras. Players follow the same steps in our install guide.
To see a log window while the game runs, set show_console = true in <GameDir>/UserData/_Redloader.cfg.
Development tools#
| Tool | Why you need it |
|---|---|
| .NET SDK 6 or newer | Builds your mod. Mods target net6, and newer SDKs (up to 10) build them fine. |
| A C# editor | Visual Studio, Rider or VS Code with the C# extension. Anything that opens a .csproj. |
| dnSpyEx | Browse the game's classes, fields and method signatures in a window. |
ilspycmd (dotnet tool install -g ilspycmd) |
Decompile SonsSdk and RedLoader. They are normal C#, so you can read exactly what each helper does. |
| UnityExplorer_Sons 4.9.4 (optional) | An in-game inspector: browse live objects, read and edit fields, run C#. F7 toggles it. Development only; never make your mod depend on it. |
| Git and a GitHub account (optional) | Version control and a public source repo. |
| Python 3 (optional) | Only if you want to publish from scripts (see Publishing). |
Where things are#
<GameDir>/
_Redloader/
net6/ RedLoader.dll, SonsSdk.dll, 0Harmony.dll, Il2CppInterop dlls
Game/ the generated interop dlls: Sons.dll, Endnight.dll, bolt.dll, UnityEngine.*.dll ...
Latest.log the log of the current session (overwritten at every start)
ErrorLog.log fatal loader errors
Mods/ installed mods: MyMod.dll + MyMod/manifest.json
Libs/ shared libraries
UserData/ _Redloader.cfg and each mod's settings file
Saves, Unity's own log (Player.log) and the game settings are in %USERPROFILE%\AppData\LocalLow\Endnight\SonsOfTheForest. Single player save slots are the numbered folders in Saves\<steamid>\SinglePlayer\.
More: 01-prerequisites.
Your first mod#
Create the project#
There are two ways. Pick one.
A. The official template
dotnet new install RedLoader.Templates@1.2.7
dotnet new sotfmod -n MyMod -g "<GameDir>" -o MyMod -c false
-g is your game folder, -c false leaves out the template's comments. Then:
- delete
Config.cs,MyModUi.csand therunfolder if you don't need settings or a UI yet; - remove the
$schemaline frommanifest.json(that URL returns 404); - keep
MyMod.csproj.userout of git, because it stores your local game path.
B. The templates of sotf-mods-skill
Copy the files from templates/ into a new folder and rename MyMod everywhere: file names, the namespace, the manifest id and the network id in Net.cs. Rename gitignore.template to .gitignore. This project builds with no warnings and already includes the save, update-loop and multiplayer patterns used later in this guide.
Write it#
Replace the mod class with this:
using RedLoader;
using SonsSdk;
using SonsSdk.Attributes;
using TheForest.Utils;
namespace MyMod;
public class MyMod : SonsMod
{
public MyMod() => HarmonyPatchAll = true;
protected override void OnSdkInitialized() => RLog.Msg("[MyMod] SDK ready");
protected override void OnGameStart() => RLog.Msg("[MyMod] world loaded");
[DebugCommand("givesticks")]
static void GiveSticks(string args) => LocalPlayer.Inventory.AddItem(392, 5, true, false, null);
}
What each line does:
SonsModis the base class RedLoader looks for.HarmonyPatchAll = trueapplies every Harmony patch in your project automatically (see Harmony).OnSdkInitializedruns once, when the title screen is ready.OnGameStartruns every time a world finishes loading.RLog.Msgwrites to_Redloader/Latest.log. Start every line with your mod's name so you can find it.[DebugCommand]adds a console command. The method must bestatic. 392 is the item id of a stick.
Build and run#
dotnet build
The build copies MyMod.dll to <GameDir>/Mods/ and manifest.json to <GameDir>/Mods/MyMod/. Then:
- Start the game. Your mod is listed in the MODS menu of the title screen.
- Open
<GameDir>/_Redloader/Latest.logand look for[MyMod] SDK ready. - Load a world.
[MyMod] world loadedappears in the log. - Press F1 to open the console, type
givesticksand press Enter. Five sticks appear in your inventory.
Mods are not hot-reloaded. After every change: close the game, build, start it again.
To get into a world faster, add --savegame <slot> to the game's launch options in Steam (right click the game, then Properties, then Launch Options). <slot> is the folder name of a single player save. Make a separate save for testing; never test on a save you care about.
Useful build variants:
dotnet build -c Release release build + ReleaseBuild/MyMod.zip
dotnet build -p:DisableCopyToGame=True build without touching the game folder
dotnet build -p:GameDir="D:\Games\Sons Of The Forest" another install folder
More: 02-project-setup.
Anatomy of a mod#
The files#
| File | Role |
|---|---|
MyMod.csproj |
The project. References RedLoader, SonsSdk, Harmony and the game's interop dlls from <GameDir> with Private=false, so none of them is copied into your build. |
Directory.Build.targets |
After each build, copies the mod into the game. In Release it also creates the zip that players install. |
manifest.json |
Tells RedLoader what your mod is. |
MyMod.cs |
The mod class. |
more .cs files |
One feature per file as the mod grows. |
Never commit or ship the interop dlls from _Redloader/Game. They are generated on each player's PC.
The manifest#
{
"id": "MyMod",
"name": "My Mod",
"author": "YourName",
"version": "1.0.0",
"description": "One or two sentences that say what the player gets.",
"loaderVersion": "0.8.6",
"type": "Mod",
"platform": "Universal",
"url": "https://sotf-mods.com/"
}
- RedLoader reads
Mods/<dll name>/manifest.json, so the folder name must match the dll name. idis unique, without spaces, and never changes after release. SOTF Mods uses it to recognise your mod: a new version must keep the sameid, and a new mod can't reuse anidthat is already taken.versionfollows SemVer (1.2.3).loaderVersionis checked: a mod that asks for a newer loader than the installed one is refused. Use0.8.6.platform:Client(the default) doesn't load on a dedicated server,Serverdoesn't load on a player's game, andUniversalloads on both.dependencieslists the ids of mods yours can't run without. Leave it out if there are none.
The lifecycle#
| Step | When it runs | Use it for |
|---|---|---|
| constructor | when the mod is loaded | flags such as HarmonyPatchAll = true, nothing else |
OnInitializeMod() |
early, before any game object exists | creating settings entries |
OnSdkInitialized() |
once, on the title screen | registering items, sounds, saves, network packets, settings UI |
OnGameStart() |
every time a world is loaded | per-world setup that needs the player |
OnSonsSceneInitialized(scene) |
on each game scene (Title, Loading, Game) |
resetting your state when the player goes back to the title screen |
IOnBeforeLoadSaveReceiver.OnBeforeLoadSave() |
right before a save is loaded | registering anything the save needs to find (your items) |
Three timing facts that cause most early bugs:
LocalPlayer.IsInWorldis false while the inventory, the blueprint book or a menu is open, during cutscenes (the intro lasts about 45 s) and after death. Logic that must keep running (timers, machines) can't depend on it.OnSdkInitializednever runs on a dedicated server, because a server has no title screen. Put your registration in aSetup()method that does nothing the second time, and call it fromOnSdkInitialized,OnBeforeLoadSaveandOnGameStart.- Static fields survive going back to the title screen and loading another world. Reset them in
OnSonsSceneInitialized(ESonsScene.Title), or data from one world leaks into the next.
The skeleton in templates/MyMod.cs shows all three: an idempotent Setup(), a reset on the title screen, a save and an update loop that runs four times per second and can't crash the game.
More: 03-sdk-api.
Finding your way around the game's code#
Most of your time goes here: finding which class does what. The interop dlls contain names and signatures only. Method bodies are stubs that call native code, so a decompiler shows you what exists, not how it works.
The golden rule: never call an API you haven't seen in a dump or in the running game. Names that sound right are often wrong. For example, the player is TheForest.Utils.LocalPlayer, not something in the Sons namespace.
Read the signatures#
- Open the dlls in
<GameDir>/_Redloader/Gamewith dnSpyEx. Most gameplay code is inSons.dll; also look inSons.Item,Sons.Construction,Sons.Gui,Sons.Electricity,Sons.Weapon,Sons.Ai.Vail,Sons.Multiplayer,Endnightandbolt. - Or use the TypeDump tool in
scripts/TypeDumpfor fast searches from the command line: members of a type, types whose name contains a word, methods with a given name. - Private fields of game classes appear as public properties with the same name (
_recipeDatabase), so you can read and write them. - Every interop method has a
[CallerCount(n)]attribute.CallerCount(0)is a warning: the native code may never call that method directly (it was inlined into its callers), so a hook on it may never run.
Watch the running game#
- UnityExplorer (F7) shows the live scene, including objects the game keeps between scenes. Use it to see how an object is built (which child has the collider, the model, the network component) and to read field values while you play.
- The console's SDK commands help too:
dump itemswrites every item to a text file in<GameDir>. - To learn when something runs or what a value is during an action, write a probe: a small Harmony patch that logs the call and its arguments. Do the action in game and read the log.
Read the SDK#
SonsSdk and RedLoader are normal managed C#. Decompile them (ilspycmd -p -o out "<GameDir>/_Redloader/net6/SonsSdk.dll") to see exactly what a helper does and when an event fires.
Write it down#
Keep a notes file in your project with every fact you verified: the type, the field, what it does and how you checked. It is the cheapest way to never repeat an hour of searching.
More: 06-reverse-engineering.
Changing the game with Harmony#
Harmony lets your code run when the game calls one of its methods:
- a postfix runs after the method and can read or change the result;
- a prefix runs before it and can skip the original by returning
false.
With HarmonyPatchAll = true in your constructor, every class marked [HarmonyPatch] is applied when the mod loads.
using HarmonyLib;
using RedLoader;
using Sons.Gameplay.Gardening;
[HarmonyPatch(typeof(GardenPlot), nameof(GardenPlot.Awake))]
static class OnPlanterAwake
{
static void Postfix(GardenPlot __instance) =>
RLog.Msg($"[MyMod] planter at {__instance.transform.position}");
}
__instance is the object whose method ran. Arguments are available by name, and the return value as ref T __result.
Rules:
- Filter first. A hook runs for every object of that type, including vanilla ones and other mods' objects. Check that it is your item or object in the first line, and leave everything else unchanged.
- Keep hooks on hot methods tiny. Each call crosses from native code into yours. No allocations, no searches.
- If a patch never fires, the method may be inlined into its callers (
CallerCount(0)). Log to confirm, then patch the caller instead. - Methods with generated names (explicit interface implementations) are patched by their string name, for example
"Sons_Save_ISaveGameSerializer_..._OnDeserialize". - Use prefixes and postfixes. Transpilers edit the wrapper's code, not the native code, so they don't do what you expect.
More: 05-il2cpp-gotchas.
Il2Cpp: the rules that save you hours#
"It compiles but crashes" almost always means one of these rules was broken.
- A wrapper is not the object.
GetComponent,transform.parentand list indexers return a new wrapper every time.a == bcan be false for the same object, andHashSet,Dictionarykeys,ContainsandDistinctcompare wrappers. Compare and key byGetInstanceID()or.Pointer. - Null checks use Unity's
==. A destroyed Unity object isn't a C# null: writeif (go == null), notgo is nullorgo?.x. - Cast with
TryCast<T>(). C#isandasonly see the wrapper's declared type. AComponentthat is really anItemRenderableneedsc.TryCast<ItemRenderable>()(null if it isn't one). - Game collections are Il2Cpp collections (
Il2CppSystem.Collections.Generic.List<T>).foreachworks; for LINQ, copy them into a normalList<T>first. - Cast delegates explicitly:
button.onClick.AddListener((UnityEngine.Events.UnityAction)OnClick);. Game events are exposed asadd_Xandremove_Xmethods. - Create Il2Cpp structs with
new X(), neverdefault:defaultwraps nothing and throws when the game reads it. - Coroutines are plain
IEnumeratormethods started with.RunCoro()(fromRedLoader).yield return nullwaits one frame. This is how you "wait a frame" after spawning something. - Edit copies while they are inactive.
Object.Instantiateof an active prefab runs itsAwakeimmediately, with the original's values. Instantiate under an inactive parent, change the fields, then activate it. - Avoid your own MonoBehaviour classes. Injected classes are invisible to the game's garbage collector: objects they alone reference get freed and the game crashes natively minutes later. Use plain C# classes driven by the update loop, keep game objects in static lists, and use hooks to learn when objects appear.
- Some Unity methods are stripped from the game even though they compile. Calling one throws
NotSupportedException: Method unstripping failed. Try it once and have a fallback. - Each interop call costs about 1 µs. In loops, cache what you read.
More: 05-il2cpp-gotchas.
Building blocks#
Short versions of what most mods need. Each one links to the verified recipe in the cookbook, and the example mods show each one inside a published mod.
The player and the inventory#
TheForest.Utils.LocalPlayer is the local player: Transform, MainCamTr (the camera), Inventory, Vitals, IsInWorld.
var inv = LocalPlayer.Inventory;
inv.AddItem(392, 2, true, false, null);
inv.RemoveItem(392, 1, false, false, false, null, false);
var sticks = inv.AmountOf(392, false, false);
When the inventory is full, DropFakeItem(id, n) drops the extra as a pickup. Item data comes from ItemDatabaseManager.ItemById(id). Common ids: stick 392, rock 393, rope 403, wire 418, duct tape 419, fish 436, cooking pot 517. ItemTools.Identifiers in the SDK has a named constant for every vanilla item.
Your own item#
The best-looking items are clones of a vanilla item with a new id, name and description:
var item = Object.Instantiate(ItemDatabaseManager.ItemById(477));
item._id = MyId;
item._name = "MyClub";
item._uiData._itemId = MyId;
item._uiData._title = "My Club";
item._uiData._translationKey = null;
item._uiData._description = "A club with a story.";
ItemTools.RegisterItem(item);
- Register it in
OnSdkInitializedand inOnBeforeLoadSave, guarded withItemTools.IsItemRegistered(MyId). If you register it only inOnGameStart, the item vanishes from the inventory when a save is loaded from a cold start. - Choose ids far from the vanilla ones (all below 1000) and from other mods' ids. Never change them after release.
ItemTools.CreateAndRegisterItem(id, name, maxAmount, icon, description)is the quick way: it clones a feather and takes your own icon.- To be seen, an item also needs models: on the inventory mat, in the hand (local and remote players) and as a pickup in the world. Each one is a recipe in the cookbook's items section.
A crafting recipe#
new ItemTools.RecipeBuilder()
.AddIngredient(392, 2)
.AddIngredient(403, 1)
.AddResult(MyId)
.Animation(ItemTools.CraftAnimations.CraftedClub)
.BuildAndAdd();
Build it once, and skip it when the recipe database already has a recipe for your result: recipes survive going back to the title screen. The result also needs a model on the crafting mat (crafting).
Buildable structures (blueprints)#
SonsSdk's CustomBlueprintManager turns a model into a blueprint the player places from the blueprint book and builds piece by piece, like vanilla structures. Each piece of the model that carries a StructureCraftingNodeIngredient is one ingredient the player adds.
Two things are mandatory:
- the SDK crash pin: SonsSdk 0.8.6 has a bug where an internal list gets freed and the game crashes when a structure is placed. The fix is one line that keeps that list in a static field;
- registration before structures load from a save, or in multiplayer before the server sends them.
Both are in custom blueprint structures. Bring the Printer and Garden Beds (its compost bins) are complete examples.
Sounds#
The game uses FMOD and has about 5700 sound events. Reuse them before shipping your own audio:
if (FMOD_StudioSystem.TryGetInstance(out var fmod, false))
fmod.PlayOneShot("event:/physics/water/water_impact_small", position, null);
Looping sounds, pitch, finding event names and your own sound files (SoundTools) are in sound.
Particles and effects#
ImpactEffectManager.SpawnSurfaceImpactObject spawns the game's own dirt, water, sparks and wood impacts. You can also build a ParticleSystem in code with a vanilla material (particles).
Input#
Read the game's own actions, so the player's key rebinding is respected:
var map = Sons.Input.InputSystem.InputMapping.@default;
if (LocalPlayer.IsInWorld && map.Take.WasPerformedThisFrame()) Use();
PrimaryAction is the left mouse button, SecondaryAction the right one, Take is pressing E, Open is holding E, Reload is R (input).
Interaction prompts#
SonsUiTools.CreateLinkUi(parent, "screen.take", distance, true) shows the game's own key icon on an object, the same one players see on vanilla pickups and doors. Pass true as the last argument, or nothing shows. Ids and custom icons: LinkUi.
Settings#
public static class Config
{
public static ConfigCategory Category;
public static ConfigEntry<float> Range;
public static void Init()
{
Category = ConfigSystem.CreateFileCategory("MyMod", "My Mod", "MyMod.cfg");
Range = Category.CreateEntry("range", 10f, "Range", "Meters.");
Range.SetRange(1f, 50f);
}
}
Call Config.Init() in OnInitializeMod, then SettingsRegistry.CreateSettings(this, null, typeof(Config)); in OnSdkInitialized. Players get a settings page under MODS, saved to UserData/MyMod.cfg. Never rename a config key after release.
Saving your data#
Implement ICustomSaveable<T> on your mod class and register it once with SonsSaveTools.Register(this):
public class Data { public int Version = 1; public List<float> Values = new(); }
public string Name => "MyMod";
public bool IncludeInPlayerSave => false;
public Data Save() => _state;
public void Load(Data data)
{
if (BoltNetwork.isClient) return;
_state = data ?? new Data();
}
- The data is stored as JSON inside the save. Use plain types (numbers, strings, lists, small classes), never Unity objects.
- Keep a
Versionfield so you can migrate old saves later. IncludeInPlayerSave => falseis world data, saved by the host.trueis per-player data, such as what the player carries.- Registering twice throws, so do it in your idempotent
Setup(). - The
isClientcheck matters in multiplayer (see Multiplayer).
Languages#
The game ships in 16 languages. Give your items real names in each language you support, with English as the fallback:
LocalizationTools.ItemsTable.AddEntry($"I_{MyId}", "My Club");
LocalizationTools.ItemsTable.AddEntry($"I_{MyId}_PLURAL", "My Clubs");
LocalizationTools.ItemsTable.AddEntry($"I_{MyId}_DESC", "A club with a story.");
The current language is LocalizationSettings.SelectedLocale?.Identifier.Code. Blueprint book page titles and structure names resolve in the Items table too. Without a plural entry the game just adds an "s" (localization).
Custom UI#
SonsSdk includes SUI, a UI toolkit for panels and settings, and you can also build Unity UI (canvas, TextMeshPro) yourself. Read the cookbook's UI section before your first panel: RegisterNewPanel(id, true) has an input-lock bug that leaves every key locked after the panel closes, and the fix is described there. Quick Inventory is a full example of a 2D UI.
Multiplayer#
Players expect co-op. A mod that only works in single player, gives clients a lesser version, or gets players disconnected, ends up with bad reviews.
Roles#
| You are | BoltNetwork.isRunning |
isServer |
isClient |
|---|---|---|---|
| Single player | false | false | false |
| Host | true | true | false |
| Dedicated server | true | true | false (and there is no local player) |
| Client | true | false | true |
"Am I in charge?" is !BoltNetwork.isClient: true in single player, on the host and on a dedicated server. Use that, not isServer, or the feature won't work in single player.
The design that works: host-authoritative#
- The host owns the state: positions, contents, timers, saved data.
- Clients send requests to the host. The host checks them, applies them and broadcasts the result.
- Every player runs the visuals locally from the state it receives: models, particles, sounds.
- Send whole state, not changes. "This bin has 7" survives a lost or repeated message; "+1" doesn't.
- Late joiners ask. A client sends "hello" in
OnGameStartand the host answers with the full state. The host also broadcasts whenever something changes. Never broadcast on a timer: a client still loading loses those messages and Bolt throws errors. - Every player needs the mod. Say so in the README and the listing.
Custom messages#
Subclass Packets.NetEvent and register it once with Packets.Register(Net.Event):
public class Net : Packets.NetEvent
{
public static readonly Net Event = new();
public override string Id => "MyMod_Net";
public void Request(int value)
{
if (!BoltNetwork.isClient) { Apply(value); return; }
var p = NewPacket(5, GlobalTargets.OnlyServer);
p.Packet.WriteByte(1);
p.Packet.WriteInt(value);
Send(p);
}
public override void Read(UdpPacket packet, BoltConnection from)
{
var kind = packet.ReadByte();
if (kind == 1 && BoltNetwork.isServer) Apply(packet.ReadInt());
}
static void Apply(int value) { }
}
NewPacket(size, target):sizeis the number of bytes you write. Read them back in the same order.- Targets:
OnlyServer(to the host),Others,Everyone, or one connection. - The host doesn't receive its own broadcasts: apply the change locally yourself. In single player
Senddoes nothing, which is whyRequesthandles that case directly. fromis the sender's connection on the host, andnullwhen the host itself is the sender.
The complete version with hello, state and request is templates/Net.cs.
For effects made of many parts (sprays, throws, debris), send one small message with the inputs and a random seed. Every player simulates the same visuals from that seed, and only the owner applies the gameplay result.
Networked objects#
Vanilla structures, blueprints and pickups placed through the game's own systems replicate by themselves. A brand new networked object needs a prefab with a BoltEntity, a unique prefab id, and EntityManager.RegisterPrefab on every player.
A joining client receives objects while it is still loading. If your prefab id isn't registered by then, the client is disconnected right after joining. The fix is to register from a Harmony prefix on Bolt.PrefabDatabase.Find, so registration happens the moment Bolt first asks (custom Bolt prefabs).
Never deactivate (SetActive(false)) an object that has a Bolt entity in the scene. It detaches for good and desyncs the session. Hide its renderers and colliders instead.
Saves in multiplayer#
A client keeps its own save and loads every registered saveable on join, even world data. That is why Load returns early when BoltNetwork.isClient: otherwise the client restores stale copies of the host's objects.
Other players' hands#
Other players see your custom held item only if their copy of your avatar knows its prop. Add it in a prefix on CoopPlayerRemoteSetup.AddHeldItem (held item).
Dedicated servers#
- Set
"platform": "Universal"in the manifest. - Remember that
OnSdkInitializeddoesn't run there (the idempotentSetup()from Anatomy of a mod covers it). - Check
!LoaderEnvironment.IsDedicatedServerbefore touchingLocalPlayer, because a server has no player. - RedLoader 0.8 doesn't run on Linux Docker servers.
More: 07-multiplayer.
Performance#
The game already pushes many PCs to their limit. A mod that costs 1 ms per frame, or freezes for 100 ms once per second, gets noticed and uninstalled. Players describe periodic scans as "stutter like a clock".
| Operation | Cost in a normal world |
|---|---|
| Objects loaded | about 2.3 million |
Object.FindObjectsOfType<T>() |
about 135 ms per call |
Resources.FindObjectsOfTypeAll<T>() |
about 145 ms per call |
| one interop call | about 1 µs |
The rules:
- Never search the scene per frame or on a timer. Learn about objects through hooks instead: a postfix on their
AwakeorStartadds them to your list. Do one search during loading for what already exists. - Gate per-frame work cheaply. Check the squared distance to the player a few times per second, and only do raycasts and heavy work when the player is near or holding your tool.
- Cache what you derive from game data (item data, icons, materials, names).
- Allocate nothing in hot paths: no LINQ, closures or string formatting per frame.
- Don't redraw UI that didn't change, and send network messages on change, not on a timer.
- Do heavy setup during loading, never in the first seconds of play or in the constructor.
To measure, time the suspect code with a Stopwatch over many runs, and compare frame time with the mod on and off in the same spot, looking in the same direction. A hitch every second means a timer with a scan, a constant cost means per-frame work, and a hitch when a menu opens means UI building.
More: 08-performance.
Testing#
Compiling proves nothing. Most bugs in SotF mods only show up in the running game: wrong casts, models that load a few frames late, hooks that never fire, multiplayer timing.
Safety first#
- Test on copies of saves, in a separate slot. Never on a save you play.
- If a test changes the game language, a setting or a file, change it back. The language setting is shared by every copy of the game on the PC.
- Remove test dlls and development mods from
Mods/when you are done.
The loop#
dotnet build, which copies the mod into the game.- Start the game with
--savegame <test slot>. It reaches the world in about 80 s. - Try the feature.
- Read
Latest.log: your lines, and any exception. - Look at it, or take a screenshot if it is visual. "The log says it worked" and "it looks right" are different checks.
- Close the game, change the code, repeat.
<GameDir>/boot.txt runs console commands at every world load, one per line (for example godmode on). In the console, vanilla commands such as godmode and settimeofday help you set up a scene.
Automated checks#
For logic you test again and again, write a small test mod that references your mod's dll, waits for the world in a coroutine, checks the result, writes [test] PASS or [test] FAIL to the log and quits the game. Keep it out of your release.
For quick experiments without restarting the game, sotf-mods-skill includes a live bridge (scripts/live): a development mod that loads a fresh experiment dll into the running game in about 5 seconds. It only runs experiments; your mod itself still needs a restart.
What to test#
- A fresh world and an existing save.
- Save, quit to desktop and load; then save, go to the main menu and load. They behave differently.
- A full inventory, death, night, a cave if your feature can be used there.
- Another language (then switch back).
- Settings changed while playing.
- A session of 10 to 15 minutes with no exceptions in the log. Some crashes only show up late.
Multiplayer tests#
You need a host and a client: a friend, a second PC or a second Steam account. Every release, check:
- the client sees everything the host sees, and the other way round;
- the client can use the feature, not just watch it;
- a client joining a save that already contains your objects isn't disconnected;
- after saving and reloading as the host, nothing is duplicated or lost;
- neither log shows errors.
More: 09-testing.
Quality and polish#
Players decide in the first minute whether a mod feels like part of the game. Sons of the Forest has almost no HUD and no magic, so match that.
- Show, don't tell. No "Item placed!" or "Mod loaded" messages. Show state in the world: a bin that fills up, a machine that hums, a light that turns on.
- No magic mechanics. Things happen for a reason the player can see (an item in a slot, a wire, water, time passing), not because a menu says so. "Build it and use it" beats "press K to get items".
- Use the game's own assets: vanilla models, FMOD sounds, particles, interaction icons, the crafting mat, the blueprint book. They match the art style and lighting for free.
- Name things the way the game does: short and concrete ("Compost Bin", not "Advanced Organic Recycler 3000"), translated, with an English fallback.
- Clients get the full feature. What one player sees, every player sees.
- Few settings, good defaults. Use the SDK's settings page and the game's own input actions.
- Be robust. Never throw from a hook or an update loop: catch the error, log it once, keep running. Removing your mod must never corrupt a save.
- Small footprint. No idle frame cost, no dependencies players have to hunt for.
- Write for players. The README says what the mod does, how to use it in game, its settings, languages, multiplayer support and how to install it (template). Screenshots show the feature in the world, in good light, without anyone's Steam name.
- Keep the code small and clear: one feature per file, clear names, no dead code or leftover test code.
More: 10-quality-and-design.
Packaging a release#
- Bump
versioninmanifest.json. - Build with
dotnet build -c Release. The zip is written toReleaseBuild/MyMod.zip. - Check the zip. It must extract straight into the game folder:
MyMod.zip
Mods/MyMod.dll
Mods/MyMod/manifest.json
Mods/MyMod/... (data files, if your mod has any)
- No
.pdb, no interop dlls, no0Harmony.dll, no UnityExplorer, no test mods. - Your csproj must have
<DebugType Condition="'$(Configuration)' == 'Release'">none</DebugType>(the templates already do). Without it the dll contains the full path of your build folder, which includes your Windows user name. - Images and other files can be embedded in the dll (
<EmbeddedResource Include="Assets\icons.png" />) and loaded withAssetLoaders.LoadTextureFromAssembly.
More: 02-project-setup.
Publishing on SOTF Mods#
SOTF Mods is where players find and download RedLoader mods. A mod has a listing (name, description, images, tags) and versions (a zip and a changelog).
Your first listing#
Create an account, then upload a new mod. Have these ready:
- a name and a one or two sentence summary that mentions multiplayer support;
- a description (your README works, without the title and images);
- screenshots (the first one is the thumbnail);
- category, tags and license;
- the multiplayer role: every player needs it, or client-side only;
- the zip and the first changelog.
The site reads manifest.json from your zip: the id becomes the mod's id on the site and the version its first version. New listings are reviewed by a moderator before they are public.
Updates#
Upload the new zip as a new version of the same mod, from your mods in the dashboard. Keep the same id and raise the version: uploading it as a new mod fails, because the id is already taken. Write the changelog for players, in short bullets about what changed for them:
- Compost bins now show how full they are.
- Fixed: clients could not open the bin in multiplayer.
No class names and no "refactored code".
Publishing from scripts (optional)#
The site has an API for creators: create an API key on the API page of your dashboard and read the creator API guide. scripts/publish-version.py uploads a version and scripts/publish-new.py creates a new listing as a draft, shows the site's checks and submits only when you ask. Both read your API key from the SOTF_API_KEY environment variable. Never paste the key into a file, a command line or a commit.
Open source (recommended)#
A public GitHub repo with the source, README, LICENSE (MIT is common) and changelog helps players trust the mod and helps other modders learn. Before every push, check that nothing private is in it: API keys, paths under your Windows user folder, emails, Steam names, saves, logs, *.csproj.user. Use templates/gitignore.template.
More: 11-publishing.
After release: maintenance#
Versions and compatibility#
- SemVer: patch (
1.0.1) for fixes, minor (1.1.0) for features, major (2.0.0) when saves or settings change incompatibly. - Never change an item id, recipe id, prefab id, save name or config key after release. Saves and players' settings depend on them. Add new ones instead.
- When your save format changes, raise its
Versionand convert old data on load instead of throwing it away.
Bug reports#
Ask for, in this order:
<GameDir>/_Redloader/Latest.logfrom the session where it happened. It is overwritten at the next start, so they must copy it before restarting. Players can share it with a private link from Share logs.- Their mod list and versions.
- Single player or multiplayer? Host, client or dedicated server?
- What they did right before.
Logs can contain the player's Steam name and paths: don't paste them into public issues.
When the game or RedLoader updates#
- Let RedLoader regenerate the interop on the next start.
- Rebuild every mod. Compile errors show renamed or removed members.
- Re-test your hooks. A method that used to be called may now be inlined.
- Check the ids you depend on.
- Publish fixed versions, saying in the changelog which game version they fix.
If RedLoader itself updates, read its release notes first (0.8.0 was a full rewrite) and raise loaderVersion only if you need the new version.
Retiring a mod#
Say so on the listing and in the README, keep the last working version downloadable, and keep its save data readable.
More: 12-maintenance.
Troubleshooting#
| Symptom | Likely cause | Fix |
|---|---|---|
| No MODS button on the title screen | RedLoader isn't loading | Check that version.dll is next to the game exe. Some Windows updates break loading (RedLoader issue #48). Check your antivirus. |
| The first starts take about 9 minutes | Defender scans the 235 generated dlls | Add a Defender exclusion for <GameDir>. |
| Your mod isn't in the MODS list | Manifest missing or in the wrong folder, or loaderVersion higher than the installed loader |
Mods/MyMod.dll and Mods/MyMod/manifest.json with matching names, loaderVersion 0.8.6. |
| Not loaded on a dedicated server | platform is Client |
Set it to Universal. |
| A console command does nothing | The method isn't static, or you are in multiplayer without cheats |
Make it static. In multiplayer the console needs cheats. |
| Your item disappears from the inventory after loading | Registered too late | Register in OnSdkInitialized and OnBeforeLoadSave. |
| A Harmony patch never fires | The method is inlined (CallerCount(0)), or you patched the wrong overload |
Confirm with a log line, then patch the caller. |
NotSupportedException: Method unstripping failed |
That Unity method was stripped from the game | Use an alternative. |
Comparing two objects with == fails, Contains misses |
Il2Cpp wrappers | Compare GetInstanceID() or .Pointer. |
| The game crashes minutes after placing your structure, or when opening the inventory | One of the two SonsSdk 0.8.6 garbage-collector bugs | Apply the fixes in 05-il2cpp-gotchas. |
| Every key stays locked after your panel closes | SUI input-lock bug | See the cookbook's UI section. |
| A client joins and is disconnected right away | One of your Bolt prefab ids isn't registered while the client loads | Register from a PrefabDatabase.Find prefix (see Multiplayer). |
| A client sees duplicates of your objects after joining | World data loaded from the client's own save | Return early in Load when BoltNetwork.isClient. |
| Clients can see the feature but not use it | The action only runs locally on the host | Send a request to the host (see Multiplayer). |
| The game stutters every second | A periodic scan of the scene | Use hooks and lists (see Performance). |
| The interaction icon never shows | refresh wasn't true, or the player turned the GUI off |
CreateLinkUi(..., true). If the GUI is off in the game settings, no mod prompt can show. |
| An item name shows as a key, or the plural is wrong | Missing localization entries | ItemsTable.AddEntry for I_<id> and I_<id>_PLURAL. |
| Your Windows user name appears inside the dll | The Release build embeds the pdb path | DebugType none in Release. |
| The game opens in another language after a test | A test changed the shared language setting | Switch it back and call PlayerPrefs.Save(). |
The game dies with nothing useful in Latest.log |
A native crash | Check ErrorLog.log, Player.log and the Application log of the Windows Event Viewer (events 1000 and 1026). |
Learn from real mods#
These five mods are open source (MIT) and follow everything in this guide. Reading real, working code is the fastest way to learn.
| Mod | What it shows |
|---|---|
| Garden Beds | Cloned tools with composed models, reusing a vanilla structure, custom blueprints, taking over the cooking pot, growth and weather, host-authoritative networking with refunds, 16 languages |
| Gone Fishing | A fishing minigame: items and hand props, water and wave detection, a fishing line, FMOD loops, a trophy mount, cosmetic-only sync, dedicated server support |
| Captives | Taking control of an NPC's AI, root-motion walking, poses, a give-items bag, tactipad orders, a rope, snapshots and requests in multiplayer |
| Bring the Printer | Items with custom icons, a blueprint structure, electricity and wiring, reusing a real game device, Bolt prefabs, host-authoritative world state |
| Quick Inventory | A full 2D UI: canvas, TextMeshPro, scrolling, drag and drop, crafting from code, taking over the inventory key, 16 languages |
13-example-mods lists every technique these mods use, with links to the exact file and method.
Community resources:
- RedLoader docs
- Community tutorials (SUI, AssetBundles and Harmony chapters). Note:
LocalPlayeris inTheForest.Utils, debug commands must bestatic, and the manual steps to addSons.dllaren't needed with the template.
If you work with an AI coding agent, give it SKILL.md: it is the same knowledge, written for agents.
Glossary#
| Term | Meaning |
|---|---|
| IL2CPP | Unity's way of shipping C# as native code. Why the game's code can't be read. |
| Interop, wrappers | Generated C# classes that mirror the game's classes and forward calls to native code. |
| RedLoader | The mod loader for Sons of the Forest. |
| SonsSdk | RedLoader's SDK for this game: SonsMod, events, and helpers for items, saves, UI and networking. |
| Harmony, prefix, postfix | The hooking library, code that runs before a game method, and code that runs after it. |
| Bolt | The game's multiplayer library. |
| Host, client, dedicated server | The player who hosts, a player who joins, a server with no local player. |
| Host-authoritative | Only the host changes the shared state; clients ask. |
NetEvent, packet |
A custom network message from SonsSdk. |
| Bolt entity, prefab id | A networked object and the number that identifies its type on every player. |
ItemData |
The definition of an item: id, names, flags, models. |
| Layout item group | The model of an item on the inventory or crafting mat. |
| Blueprint, crafting node | A structure from the blueprint book, and its ghost that the player fills with ingredients. |
| LinkUi | The game's interaction icon (the key shown on objects). |
| FMOD event | A game sound, named like event:/physics/water/water_impact_small. |
Latest.log |
RedLoader's log of the current session, in <GameDir>/_Redloader/. |
| SemVer | Version numbers as major.minor.patch. |
Release checklist#
Copy this into every release.
- Works in single player, as host and as client, and the client can use the feature, not just see it.
- A client joining a save that already has your objects isn't disconnected.
- Save, quit and load, then save, go to the menu and load: nothing duplicated or lost.
- No exceptions in
Latest.logafter a session of 10 to 15 minutes. - No measurable frame cost while idle, no periodic stutter.
- No HUD text spam; state shown in the world with vanilla icons, sounds and models.
- Every visible string translated, with an English fallback.
- SDK crash fixes applied if you use custom blueprints or
ItemBuilder.AddInventoryItem. -
versionbumped,loaderVersion0.8.6,platformcorrect,idunchanged. - Zip layout correct: no pdb, no interop dlls, no local paths in the dll.
- README and player-facing changelog written.
- Test mods, development mods and test saves removed; the game's settings restored.
- Repo checked for keys, paths, emails and Steam names before pushing.