Show / Hide Table of Contents

APIs

This document gives an overview of the various utility APIs the mod loader provides. It does not contain information about major elements, like Blocks or Entities. The networking API is explained in its own document. It is also not a method-by-method reference, for that see the API documentation.

Keys

The mod loader supports remappable key-bindings. When a mod supports keyboard shortcuts, it should use this API to handle them, this automatically makes the shortcuts more user-friendly by making them rebindable.

Note: As of now there is no UI for players to remap key-bindings. It is nevertheless recommended to use this API, as it still allows remapping keys through the config file and any mod using it will automatically take advantage of the UI when it is added.

Each key-binding needs to be declared in the mod manifest first:

<Mod>
    <Keys>
        <Key name="some-key" defaultModifier="LeftControl" defaultTrigger="L" />
    </Keys>
</Mod>

The name property must be unique among the keys of a single mod. The name may not contain the | character. The defaultModifier and defaultTrigger values may be any Unity KeyCode. See the Unity documentation for a full list.

defaultModifier may be omitted, the default value is None. None as a modifier value causes the modifier to be ignored. None as trigger value is equivalent to unbinding the key, it will never be triggered.

To access the keybindings in code, use the ModKeys API. Call ModKeys.GetKey(name) to get a reference to the specified key. If you plan on checking the key frequently (e.g. every frame), it is advisable to store the returned reference, as each call to GetKey requires two dictionary lookups.

The returned ModKey object provides the IsDown, IsPressed and IsReleased properties. These correspond to GetKey, GetKeyDown and GetKeyUp in Unity's Input class respectively.

Configuration

The Configuration API provides a way to store persistent configuration data. It is not mean for storing large amounts of data, please use normal file I/O for that (see IO). To use the Configuration API, call Configuration.GetData(). This returns an XDataHolder object, a simple key-value store that is also used to store custom information in levels and machines. Once retrieved, values can be set and read from the object freely. The configuration is automatically saved when the game exits, but is is also possible to manually call Configuration.Save() to save it instantly.

IO

The game prevents mods from using most IO-related methods from the .NET framework to protect the files and computers of players. It is still possible to do some file IO using the ModIO class and whitelisted classes from the framework.

In modded code, it is permissible to use the Stream, Text{Reader, Writer} and Binary{Reader, Writer} classes. Using these on its own, it is not possible to open a file for reading or writing, so the ModIO class provides methods to do this.

The methods in ModIO are mostly analogous to those in the File, Directory and WebClient classes (in System.IO and System.Net) of the .NET framework. Parameters and usage are explained in the documentation for those.

There are two directories a mod is allowed to access: Its own root directory, as well as a data directory provided by the mod loader.

The root directory access can be used to for example load additional resource files outside of the mod loader resource handling system.

The data directory should be used for storing additional persistent files. The reason for not using the mod root directory for this is that, when the mod is installed from the Steam workshop, it is possible that Steam may overwrite any additional files, especially when the mod is updated for example.

The important difference is that any paths taken as arguments by those methods are always interpreted relative to the mod's root directory (the one where the mod manifest is located) and no paths that traverse outside of it are allowed.

Additionally, the WebClient methods are implemented as static wrappers instead of exposing a WebClient object. Instead of setting events on the object, the static wrappers take (optional) event handler arguments for completion and progress events. It is also not allowed to access local files using the Download* methods, even if they are located in the mod directory.

Resources

The ModResource API can be used to easily load supported resource types. Resources to be loaded using this system need to be declared in the mod manifest file:

<Mod>
    ...
    <Resources>
        <Mesh name="some-name" path="someMesh.obj" />
    </Resources>
</Mod>

Available resource types are Mesh, Texture, AudioClip, and AssetBundle. The name must be unique within a mod, like an ID. The path is relative to the Resources/ directory.

It is possible to manually access these resources using the ModResource class. There is a ModResource.getX(string name) method for each of the supported types, e.g. GetMesh, GetTexture, etc. These methods return a ModX (ModMesh, ModTexture, etc.) object, all of which inherit from the basic ModResource.

Note that returned textures are non-readable by default, specify readable="true" as attribute in the manifest Resource section for a texture you need to modify or read in code.

Along with accessors to get the loaded resource (in Unity's type for them), they have the following interface:

  • Name (String): Returns the name of the resource.
  • Type (ResourceType): Type of the resource.
  • Loaded (Boolean): Indicates whether the resource has finished loading. Will also be true if an error occurred while loading the resource.
  • HasError (Boolean): Indicates whether an error occurred while loading the resource.
  • Error (String): If an error occurred, an error message.
  • Available (Boolean): Like Loaded but false if an error occurred.
  • OnLoad (event, Action): Event called when the resource has finished loading. Also called when an error occurs while loading the resource. If an event handler is registered to this event and the resource has already been loaded, the handler is immediately called.

In addition to that, the ModResource class also contains the static event OnResourceLoaded (Action<ModResource>). It behaves like the OnLoad event for a single resource but is called for all resources of a mod. It can be used to do generic error handling for example.

For one of the the most common use cases, ModResources also have a SetOnObject method. This can be used on all resource types except ModAssetBundles.

It will set the resource on the given object once it has finished loading, thereby automatically handling the case that a resource may take a longer time to load than usual.

Additionally, it automatically handles the given object being instantiated as well. If the object is cloned by Unity while the resource has not finished loading, the resource will automatically also be set on all copies of the object once it has loaded.

Console

The ModConsole class allows mods to interact with the in-game console.

The Log method simply prints the given message to the console on its won line.

RegisterCommand can be used for custom console commands. It requires a command name, a handler and some help text.

For every command someCommand that is registered, 3 commands actually become available to the user: someCommand, <modName>:someCommand, and <modId>:someCommand.

This is done to allow different mods to ad the same command. If this happens, the basic someCommand version will automatically be changed ot only output some informational text and the user has to call mod1:someCommand or mod2:someCommand instead, depending on which one they want to call.

The command handler mus tbe a method (or lambda, ...) taking a a string[]. This array contains the arguments passed on the console. Arguments are separated by spaces, and quoting of an argument containing spaces is automatically handled.

Mods

The Mods class provides methods to query the state of other loaded mods.

Using this, it is possible to perform additional actions depending on the presence of other mods, adding integration between mods without creating a hard dependency.

When interacting with classes from assemblies of other mods, one needs to be very careful in order to not create a hard dependency. Make sure methods accessing other assemblies are only loaded/called if the mod is actually present.

Game

The Game class provides various methods to interact with the game. The UI subclass is documented below.

Simulation State

There are a variety of properties and methods to control the current simulation state: IsSimulating, IsSimulating{Local,Global}, {Start,End}Simulation{Local,Global}().

These are pretty self-explanatory, note that it is possible to set the properties, this is equivalent to calling the appropriate methods. Calling the methods can throw exceptions for invalid operations, for example trying to start local sim while in global sim or vice-versa.

Additionally, IsSetToLocalSim and ToggleLocalSimState() control whether the game is currently set to use local simulation or join global simulation.

Multiverse Playlists

The NextPlaylistLevel() and PreviousPlaylistLevel() methods can be used to programmatically control the multiverse playlist mode. They have to be called on the host, and will just not do anything if not playlist is set up.

The GetPlaylist() method can be used to get the current playlist, as a list of paths to level files.

Multiverse Level Progress

The GetCurrentProgress(MPTeam) and GetCurrentProgress() methods can be used to check the level progress in a multiplayer game, as set by the logic system.

Useful raycasts

BlockEntityRaycast and BlockEntityMouseRaycast are utility functions to perform raycasts to detect only blocks and entities (using the Game.BlockEntityLayerMask mask).

There is one caveat that applies to blocks: The game uses stripped-down versions of blocks that are part of other players' machines on all clients (but not the host). These do not have any colliders and can thus not be detected using raycasts. If it is necessary to perform a raycast that can detect all blocks from a client, use the ModNetworking API to perform it on the host and transmit the result.

UI

The UI subclass provides methods for easily interacting with the game UI from code. For example, specific block tabs or level editor categories can be opened, or block types / level editor objects can be selected.

If the level editor-related methods are called when not in multiplayer, or any method is called while in a menu scene, nothing is done.

GamePrefabs and GameMaterials

The GamePrefabs class provides easy access to certain useful game objects that are frequently used in the game. Currently, these are projectiles as well as different explosions.

It contains two methods: InstantiateExplosion and InstantiateProjectile. Both spawn a GameObject of the given type and return it.

The GameMaterials class similarly provides access to the shaders used in the game, along with some sample Material setups that can then be customized as desired.

The shaders can simply be accessed in the static GameMaterials.Shaders class.

Materials can be accessed using the GetMaterial method. It returns a copy of the appropriate material specified.

Wrapper classes

The game generally represents objects such as blocks, entities, machines, or players using a variety of internal classes.

Since these are considered not stable and can change with any update to enable new game features or for optimization purposes, the Common, Blocks, and Levels namespaces in Modding provide wrapper classes to represent these objects that have a stable (and modder-friendly) API.

For the full documentation of each of these classes, see Modding.Common, Modding.Blocks, and Modding.Levels.

ModUtility

The ModUtility class provides some miscellaneous useful methods.

See the API documentation for a list and detailed information.

Back to top Generated by DocFX