Create a custom startup locale selector
Control which language the application starts in.
Read time 2 minutesLast updated 13 days ago
Control which language the application starts in.
At startup, the selectors in the Localization settings run in order and the first one that returns an enabled locale decides the language. This example writes a selector that restores the user's saved choice, with the same pattern as the built-in Player Pref selector. Use it as a starting point to store the choice in a save file, a cloud profile, or your own settings system.
Prerequisites
Before you start, make sure you have the following:
- Localization settings with two or more locales. Refer to Get started with localization.
Write the selector
Implement to choose the locale, and to run one-time setup after initialization. In this example, the setup subscribes to locale changes so the selector saves them:
IStartupLocaleSelectorIStartupLocaleInitialize[Serializable] public class SaveFileLocaleSelector : IStartupLocaleSelector, IStartupLocaleInitialize { [SerializeField] string m_PreferenceKey = "preferred-language"; public Locale GetStartupLocale(LocalizationSettings settings) { // Returning null lets the next selector in the list decide. var code = PlayerPrefs.GetString(m_PreferenceKey); return string.IsNullOrEmpty(code) ? null : settings.GetLocale(new LocaleIdentifier(code)); } public void PostInitialize(LocalizationSettings settings) { // Store later language changes so the next launch starts in the player's language. LocalizationSettings.SelectedLocaleChanged += locale => PlayerPrefs.SetString(m_PreferenceKey, locale.Code); } }
The selector class must follow two constraints:
- It must have the attribute. The settings serialize the selector list, and serialized fields, such as
[Serializable], appear as options in the settings UI.m_PreferenceKey - It must return when it has no locale to offer. A
nullreturn passes the decision to the next selector, and localization treats a disabled locale the same way.null
Register the selector
To register your selector:
- Open Edit > > Localization.Project Settings
?
- Add your selector to the startup selectors list. It appears in the add menu automatically.
- Move the saved-choice selector to the top of the list, so an explicit choice takes priority over the device language. Keep the System Locale Selector after it for first launch.
Test the selector
This selector follows the same pattern as the built-in Player Pref Locale Selector, but writes the choice to a file instead of . To verify that it persists the choice:
PlayerPrefs- Enter Play mode.
- Change the current language, for example with the language switcher in the Editor toolbar or with the built-in language selection controls.
- Exit Play mode and enter it again. The application starts in the language you selected.
- Delete the save file the selector wrote to, then enter Play mode again. The next selector in the list decides the language.