Using translations

Unturned Plugin Development #6

MCrow • 5 months ago

Every plugin should have a way to customize messages or translate them to other languages. You probably noticed that every RocketMod plugin generates translations file in its directory, for example: Rocket/Plugins/Example/Example.en.translation.xml.

Very unpopular feature of RocketMod is that you can specify the language code in the Rocket.config.xml file. When you change <LanguageCode>en</LanguageCode> to <LanguageCode>pl</LanguageCode> for example, RocketMod will generate and use Example.pl.translation.xml file instead of Example.en.translation.xml. Still most server owners just leave it as en and eventually translate this .en file to their language.

Adding translations

You can only add translations only by overriding the DefaultTranslations property in your plugin class. The DefaultTranslations property is a dictionary that contains translations for your plugin. The key is the translation key and the value is the translation text.

Here is an example of default translations for the MaxskillsCommand command:

public override TranslationList DefaultTranslations => new()
{
    { "PlayerNotFound", "Failed to find any player with the name {0}." },
    { "MaxskillsInvalid", "You must specify a player." },
    { "MaxskillsSuccess", "Maxskills give to you." },
    { "MaxskillsSuccessOther", "Maxskills given to {0}." }
};

Using translations

To use translations in your plugin you need to use the Translate method from the plugin class instance. The Translate method has 2 parameters: the translation key and the parameters. The translation key is the key from the DefaultTranslations dictionary and the parameters are the values that will replace the {0}, {1}, etc. in the translation text.

The {0}, {1} etc. are placeholders for the parameters. For example, the MaxskillsSuccessOther translation has {0} placeholder. When you call Translate("MaxskillsSuccessOther", "MCrow") then the {0} will be replaced with MCrow.

To access the plugin instance you need to make a singleton in the plugin class. You need to add a static property that will return the instance of the plugin class. You can do that by adding the following code to the plugin class:

Then you can access the plugin instance from anywhere in your plugin by using ExamplePlugin.Instance.

Here is an example of using translations in the MaxskillsCommand command:

First at the top of the method we declare pluginInstance variable to not repeat ExamplePlugin.Instance multiple times. Then we use pluginInstance.Translate method to get the translation text.