using System; using UnityEngine; using UnityEngine.UI; [RequireComponent(typeof(Text))] public class LocalizationUIText : MonoBehaviour { [Serializable] public class TextFormatingTags { public string tag = "_X_"; public string replacetext = "X"; } public string key; public bool isUpper; public TextFormatingTags[] textFormatingTags; private string tempLanguage = ""; private Text textComp; private void Start() { if (!(LanguageManager.Instance != null)) { return; } textComp = GetComponent(); if ((bool)textComp) { if (string.IsNullOrEmpty(LanguageManager.Instance.GetText(key))) { textComp.text = "Key error: " + key; } else if (isUpper) { textComp.text = CheckAndUseFormatingText(LanguageManager.Instance.GetText(key)).ToUpper(); } else { textComp.text = CheckAndUseFormatingText(LanguageManager.Instance.GetText(key)); } } } private string CheckAndUseFormatingText(string orgText) { if (textFormatingTags.Length == 0) { return orgText; } for (int i = 0; i < textFormatingTags.Length; i++) { string oldValue = textFormatingTags[i].tag; orgText = orgText.Replace(oldValue, textFormatingTags[i].replacetext); } return orgText; } private void OnEnable() { Translate(); } private void Translate() { if (!(LanguageManager.Instance != null)) { return; } tempLanguage = LanguageManager.Instance.currentLanguage; Text component = GetComponent(); if ((bool)component) { if (string.IsNullOrEmpty(LanguageManager.Instance.GetText(key))) { component.text = "Key error: " + key; } else if (isUpper) { component.text = CheckAndUseFormatingText(LanguageManager.Instance.GetText(key)).ToUpper(); } else { component.text = CheckAndUseFormatingText(LanguageManager.Instance.GetText(key)); } } } public void SetKey(string key) { if (!(LanguageManager.Instance == null)) { this.key = key; if (isUpper) { GetComponent().text = CheckAndUseFormatingText(LanguageManager.Instance.GetText(key)).ToUpper(); } else { GetComponent().text = CheckAndUseFormatingText(LanguageManager.Instance.GetText(key)); } } } private void FixedUpdate() { if (tempLanguage != LanguageManager.Instance.currentLanguage) { Translate(); } } }