Localization in Unity

Hello, game maker!
In this article, you will learn how to make comfortable localization in your game.

Problem:

Language is perhaps one of the main thresholds for players, if your game supports English, many will be able to understand what is happening in it, but what about the audience that does not speak this language? And playing a game with native language support is always more enjoyable.
For an inexperienced developer, it may be very unclear how to implement the multilingualism of your game, sometimes this question arises when part of the game is already finished, in such cases the localization system should be an “add-on” to the existing code base, and not rebuild it in connection with a new task …

Solution ways:

As with any problem in game programming, we can find a lot of solutions, so here too.

1) Assets, a powerful Unity tool that allows you to use functionality implemented by someone in your project, localization is no exception, for example simple localizationhowever, this solution can be tricky if the project is small and will take more time than your own implementation, and it also does not provide an understanding of how localization works in games.

2) Different versions of the game in different languages. A dubious method, but before it was often used to save memory and simplify the game itself, but that time has passed and now an additional script and file in the game’s resources is a trifle that can save a lot of time searching for text to be translated in the code.

3) Translation by file, in my opinion, is the best way, which we will implement below with our own hands. The translator will simply work with one text file.

Solution:

First, we need to create a csv file in which we will store the translation of all text labels in the game. This can be done in Excel or simply in notepad (after all, csv is a text file):

The file structure is as follows: the first line is the names of the columns, ” ; “- separator of elements from different columns on the same line. id – a unique indicator of the text, the translations of which are stored in the corresponding columns of the same line.

When you place Localization.csv in Resources (there I created the “Localization” folder and already placed csv in it) of your game, you will see that Unity perceives your file as a Text Asset, as it should be, Unity has its own loading methods for it , so we don’t have to do the parsing.

So, before directly localizing the text, we need to implement the language selection:

// Language_changer.cs
using UnityEngine;

public class Language_changer : MonoBehaviour
{
    public void Set_RU()
    {
    		// сохраняем пару ключ-значение
        PlayerPrefs.SetString("GameLanguage", "RU");
        // выведем сведетельство того, что игра увидела смену языка
        Debug.Log("Language changed to RUSSIAN");
    }
    public void Set_EN()
    {
        PlayerPrefs.SetString("GameLanguage", "EN");
        Debug.Log("Language changed to ENGLISH");
    }
}

This script must be attached to the prefab, and hang it on the buttons responsible for choosing the language:

Finally, you can write the localizer script itself, which later we will hang on everything that has a Text field …

// Localizator.cs
using UnityEngine;
using UnityEngine.UI;
using System.Text.RegularExpressions;

public class Localizator : MonoBehaviour{
    public string id;
    void Awake(){  // если язык выбран...
        if (PlayerPrefs.HasKey("GameLanguage")){
            string GameLanguage = PlayerPrefs.GetString("GameLanguage");  //  RU/EN
            change_text(localized_text(id, GameLanguage));
        }else{  // если язык не выбран то английский по умолчанию
            change_text(localized_text(id, "EN"));
        }
    }

    private void change_text(string new_text){
        // вставляем текст в текстовое поле объекта на котором висит скрипт
        GetComponent<Text>().text = new_text;
    }
  
    private string localized_text(string id, string lang){  // вытаскиваем из таблицы значение
      // читаем из Resources/Localization/Localization.csv
      TextAsset mytxtData=(TextAsset)Resources.Load("localization/localization");
        string loc_txt=mytxtData.text;
        string[] rows = loc_txt.Split('n');
        for (int i = 1; i < rows.Length; i++);
            string[] cuted_row = Regex.Split(rows[i], ";");
            if(id == cuted_row[0]){
                if(lang == "EN"){
                    return cuted_row[1];
                }else if(lang == "RU"){
                    return cuted_row[2];
                }
                break;
            }
        }
        return "translation not found";  // если перевод не найден в таблице
    }
}

Ready! All that is needed for localization is simply to attach the script to the object (which has a Text field), specify the id (public variable of the script) and enter the id with the appropriate translations into the localization file.

example of use
example of use

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *