We’ll need:
– a public static Dictionary that stores all of the game’s words
– a public static Function that sets the game language
– a public static Function that gets words from the Dictionary when you need them
So first… create a C# public static class named LanguageDictonary:
[code language=”csharp”]
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public static class LanguageDictionary {
//The words will be stored in this Dictionary
public static Dictionary<string, string> stringList = new Dictionary<string, string>();
//This is the default game language (english)
public static SystemLanguage defaultLanguage = SystemLanguage.English;
//This list stores the supported languages
public static List<SystemLanguage> supportedLanguages = new List<SystemLanguage>();
//this class sets the language and add its words to the Dictionary
public static void SetLanguage (SystemLanguage language) {
//check if the language is in the supported languages list
supportedLanguages.Add (SystemLanguage.English);
supportedLanguages.Add (SystemLanguage.Spanish);
if (!supportedLanguages.Contains (language))
language = defaultLanguage;
//Here you add the english translations
if (language == SystemLanguage.English) {
stringList.Add ("Yes", "Yes");
stringList.Add ("No", "No");
}
//here you add the spanish translations
else if (language == SystemLanguage.Spanish) {
stringList.Add ("Yes", "Yes");
stringList.Add ("No", "No");
}
}
//this function gets words from the dictionary
public static string GetTranslation (string stringToTranslate) {
if (stringList.ContainsKey (stringToTranslate))
return stringList [stringToTranslate];
else
return stringToTranslate;
}
}
[/code]
The first function, SetLanguage (), MUST be called at the beginning of the game, to set the language. Example:
[code language=”csharp”]
//Supposing you want to get the user’s system language
SetLanguage (Application.systemLanguage);
//Supposing you want to set the language manually
SetLanguage (SystemLanguage.English);
[/code]
The second function, GetTranslation (), must be called whenever you need a translated word. Example:
[code language=”csharp”]
//Supposing you want to put translated text in a Text component
GetComponent<Text>().text = GetTranslation ("Yes");
[/code]
That’s it! If you have any questions, leave a comment below.
You have to call the method LanguageDictionary.SetLanguage (); to set the language before “asking” for the text to be translate.
I recommend you doing it during the game intro or before any translation call.
Works fine!
Thanks!
Marcelo, muito obrigado! estou no rumo de terminar e publicar meu primeiro jogo para android, fiz um sisteminha para ter varias línguas usando arquivos XML que só funcionou no PC e não no android. Usando o Dictionary, agora, ta tudo nos trinques! valeu!