Change locale at any time
Verification environment
- Windows
-
- Windows 11
- Unity Editor
-
- 2021.3.12f1
- Input System (Unity Technologies)
-
- 1.4.3
- Localization (Unity Technologies)
-
- 1.3.2
Prerequisites for this tip
The following settings have been made in advance as a premise for the description of this tip.
Prerequisite knowledge and preparation
This tip assumes localization of the following text: First, please refer to the following tips to prepare to display localized text.
Placing buttons for changing locale
If you run it in the Unity Editor, you can change the locale in the upper right corner of the screen, but after building the game, it does not have that function and you need to prepare it yourself. This time, I will place a button to switch between the three languages "Japanese (ja)", "English (en)", and "Spanish (es)" and click to switch them.
Scripting for buttons
Make sure that the target method is called when you click the button. This is a general-purpose procedure, so I will omit the details. See the following tips for detailed instructions.
ButtonEvent
Create a script with the name .
using UnityEngine;
public class ButtonEvent : MonoBehaviour
{
<summary>Japanese (ja) ボタンをクリックしたとき。</summary>
public void OnClickJa()
{
}
<summary>English (en) ボタンをクリックしたとき。</summary>
public void OnClickEn()
{
}
<summary>Spanish (es) ボタンをクリックしたとき。</summary>
public void OnClickEs()
{
}
}
Assign each method to a button click.
Handling locale changes
Modify the code as follows:
using UnityEngine;
using UnityEngine.Localization;
using UnityEngine.Localization.Settings;
public class ButtonEvent : MonoBehaviour
{
<summary>Japanese (ja) ボタンをクリックしたとき。</summary>
public void OnClickJa()
{
LocalizationSettings.SelectedLocale = Locale.CreateLocale("ja");
}
<summary>English (en) ボタンをクリックしたとき。</summary>
public void OnClickEn()
{
LocalizationSettings.SelectedLocale = Locale.CreateLocale("en");
}
<summary>Spanish (es) ボタンをクリックしたとき。</summary>
public void OnClickEs()
{
LocalizationSettings.SelectedLocale = Locale.CreateLocale("es");
}
}
The change itself is simple LocalizationSettings.SelectedLocale
and can be switched by simply setting the target Locale
in the property.
Locale
Locale.CreateLocale
can be created by setting the name of the locale in the method.
However, since the locale change process is asynchronous,LocalizationSettings.SelectedLocale
the next process that sets does not mean that the locale has already been completely switched.
Be careful if you are doing locale-dependent operations.
Run and verify
This is all there is to it, so please run it and check the movement. In the upper right corner of the game screen, you can see that the various resources switch dynamically in the same way as when you change the locale.