LocalizationManager.cs 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. using UnityEngine;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Xml.Linq;
  5. public class LocalizationManager : MonoBehaviour
  6. {
  7. public static LocalizationManager Instance { get { return instance; } }
  8. public int currentLanguageID = 0;
  9. [SerializeField]
  10. public List<TextAsset> languageFiles = new List<TextAsset>();
  11. public List<Language> languages = new List<Language>();
  12. private static LocalizationManager instance; // GameSystem local instance
  13. void Awake() {
  14. if (instance == null) {
  15. instance = this;
  16. DontDestroyOnLoad(this);
  17. }
  18. // This will read each XML file from the languageFiles list<> and populate the languages list with the data
  19. foreach (TextAsset languageFile in languageFiles) {
  20. XDocument languageXMLData = XDocument.Parse(languageFile.text);
  21. Language language = new Language();
  22. language.languageID = System.Int32.Parse(languageXMLData.Element("Language").Attribute("ID").Value);
  23. language.languageString = languageXMLData.Element("Language").Attribute("LANG").Value;
  24. foreach (XElement textx in languageXMLData.Element("Language").Elements()) {
  25. TextKeyValue textKeyValue = new TextKeyValue();
  26. textKeyValue.key = textx.Attribute("key").Value;
  27. textKeyValue.value = textx.Value;
  28. language.textKeyValueList.Add(textKeyValue);
  29. }
  30. languages.Add(language);
  31. }
  32. }
  33. // GetText will go through each language in the languages list and return a string matching the key provided
  34. public string GetText(string key) {
  35. foreach (Language language in languages) {
  36. if (language.languageID == currentLanguageID) {
  37. foreach (TextKeyValue textKeyValue in language.textKeyValueList) {
  38. if (textKeyValue.key == key) {
  39. return textKeyValue.value;
  40. }
  41. }
  42. }
  43. }
  44. return "Undefined";
  45. }
  46. }
  47. // Simple Class to hold the language metadata
  48. [System.Serializable]
  49. public class Language
  50. {
  51. public string languageString;
  52. public int languageID;
  53. public List<TextKeyValue> textKeyValueList = new List<TextKeyValue>();
  54. }
  55. // Simple class to hold the key/value pair data
  56. [System.Serializable]
  57. public class TextKeyValue
  58. {
  59. public string key;
  60. public string value;
  61. }