Modding:Modder Guide/APIs/Config
< Modding:Modder Guide | APIs
Jump to navigation
Jump to search
Revision as of 22:16, 27 May 2018 by Pathoschild (talk | contribs) (move content from Modding:Modder Guide/APIs (main author is Pathoschild, with contributions from KNakamura and Kalthramis))
- Get started
- Game fundamentals
- Test & troubleshoot
- Release
- API reference
- Basic SMAPI APIs:
- Advanced SMAPI APIs:
- Specific guides
Configuration
You can let users configure your mod through a config.json file. SMAPI will automatically create the file and take care of reading, normalising, and updating it.
- Basic configuration
- Here's the simplest way to use config.json:
- Create your model. This is just a C# class with properties for the config options you want, and it can contain almost anything from a few boolean fields to a complex object graph (You should try to keep it simple for your users, though).
You can set defaults directly:class ModConfig { public bool ExampleBoolean { get; set; } = true; public float ExampleFloat { get; set; } = 0.5f; }
...or with a constructor:
class ModConfig { public bool ExampleBoolean { get; set; } public float ExampleFloat { get; set; } public ModConfig() { this.ExampleBoolean = true; this.ExampleFloat = 0.5f; } }
- In your ModEntry::Entry method, add this line to read the config options:
ModConfig config = helper.ReadConfig<ModConfig>();
Values are then accessible through the value config. Example:
public class ModEntry : Mod { public override void Entry(IModHelper helper) { ModConfig config = helper.ReadConfig<ModConfig>(); float exampleF = config.ExampleFloat; } }
- Create your model. This is just a C# class with properties for the config options you want, and it can contain almost anything from a few boolean fields to a complex object graph (You should try to keep it simple for your users, though).
- Custom JSON files
-
Sometimes one config.json isn't enough, or you need to store data that's not meant to be edited by the user. This is pretty easy using the ModHelper:
- Create your model (just like the previous section).
- In your mod code, use this.Helper to read and write to a named file:
Note that ReadJsonFile will return null if the file doesn't exist. The above example will create a default instance if that happens; if you don't want to do that, just remove the
// read file var model = this.Helper.ReadJsonFile<ModData>("data.json") ?? new ModData(); // save file (if needed) this.Helper.WriteJsonFile("data.json", model);
?? new ModData()
part.
- Per-save JSON files
-
You can create per-save files by using the save ID in the name. If you specify a folder path (relative to your mod folder), SMAPI will create the folders automatically if needed.
For example, here's a typical per-save data file:
// read file var model = this.Helper.ReadJsonFile<ModData>($"data/{Constants.SaveFolderName}.json") ?? new ModData(); // write file (if needed) this.Helper.WriteJsonFile($"data/{Constants.SaveFolderName}.json", model);