UILocalize.cs 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. using TMPro;
  2. using UnityEngine;
  3. namespace ICTS.Localization
  4. {
  5. public class UILocalize : MonoBehaviour
  6. {
  7. /// <summary>
  8. /// Localization key.
  9. /// </summary>
  10. public bool Upper;
  11. public string key;
  12. string mLanguage;
  13. bool mStarted = false;
  14. /// <summary>
  15. /// This function is called by the Localization manager via a broadcast SendMessage.
  16. /// </summary>
  17. void OnLocalize(Localization loc) { if (mLanguage != loc.currentLanguage) Localize(); }
  18. /// <summary>
  19. /// Localize the widget on enable, but only if it has been started already.
  20. /// </summary>
  21. void OnEnable() { if (mStarted && Localization.instance != null) Localize(); }
  22. /// <summary>
  23. /// Localize the widget on start.
  24. /// </summary>
  25. void Start()
  26. {
  27. mStarted = true;
  28. if (Localization.instance != null) Localize();
  29. }
  30. /// <summary>
  31. /// Force-localize the widget.
  32. /// </summary>
  33. public void Localize()
  34. {
  35. Localization loc = Localization.instance;
  36. TMP_Text lbl = GetComponent<TMP_Text>();
  37. // If no localization key has been specified, use the label's text as the key
  38. if (string.IsNullOrEmpty(mLanguage) && string.IsNullOrEmpty(key) && lbl != null) key = lbl.text;
  39. // If we still don't have a key, leave the value as blank
  40. string val = string.IsNullOrEmpty(key) ? "" : loc.Get(key);
  41. if (lbl != null)
  42. {
  43. // If this is a label used by input, we should localize its default value instead
  44. TMP_InputField input = transform.GetComponent<TMP_InputField>();
  45. if (input != null && input == lbl)
  46. {
  47. if (Upper)
  48. {
  49. input.text = val.ToUpper();
  50. }
  51. else
  52. {
  53. input.text = val;
  54. }
  55. input.text = val;
  56. }
  57. else
  58. {
  59. if (Upper)
  60. {
  61. lbl.text = val.ToUpper();
  62. }
  63. else
  64. {
  65. lbl.text = val;
  66. }
  67. }
  68. }
  69. mLanguage = loc.currentLanguage;
  70. }
  71. }
  72. }