65 lines
1.4 KiB
C#
65 lines
1.4 KiB
C#
using UnityEngine;
|
|
using UnityEngine.UI;
|
|
|
|
[DisallowMultipleComponent]
|
|
[RequireComponent(typeof(Text))]
|
|
public class LocalizedText : MonoBehaviour
|
|
{
|
|
[SerializeField] private string localizationKey;
|
|
[TextArea]
|
|
[SerializeField] private string fallbackText;
|
|
|
|
private Text _text;
|
|
|
|
private void Awake()
|
|
{
|
|
_text = GetComponent<Text>();
|
|
}
|
|
|
|
private void OnEnable()
|
|
{
|
|
LocalizationService.EnsureInitialized();
|
|
LocalizationService.LanguageChanged += HandleLanguageChanged;
|
|
Refresh();
|
|
}
|
|
|
|
private void OnDisable()
|
|
{
|
|
LocalizationService.LanguageChanged -= HandleLanguageChanged;
|
|
}
|
|
|
|
public void Refresh()
|
|
{
|
|
if (_text == null)
|
|
{
|
|
_text = GetComponent<Text>();
|
|
}
|
|
|
|
if (_text == null)
|
|
{
|
|
return;
|
|
}
|
|
|
|
string fallback = string.IsNullOrEmpty(fallbackText) ? _text.text : fallbackText;
|
|
|
|
if (string.IsNullOrWhiteSpace(localizationKey))
|
|
{
|
|
_text.text = LocalizationService.LocalizeLiteral(fallback);
|
|
return;
|
|
}
|
|
|
|
if (LocalizationService.TryGet(localizationKey, out string localized))
|
|
{
|
|
_text.text = localized;
|
|
return;
|
|
}
|
|
|
|
_text.text = LocalizationService.LocalizeLiteral(fallback);
|
|
}
|
|
|
|
private void HandleLanguageChanged(string languageCode)
|
|
{
|
|
Refresh();
|
|
}
|
|
}
|