using TMPro; using UnityEngine; using UnityEngine.UI; [DisallowMultipleComponent] public class LocalizedLiteralText : MonoBehaviour { [SerializeField] private string sourceText; [SerializeField] private bool useTmp; [SerializeField] private bool captured; [SerializeField] private float refreshIntervalSeconds = 0.25f; private string _lastAppliedText; private float _nextRefreshAt; public void CaptureIfNeeded(string currentText, bool isTmp) { if (captured) { return; } sourceText = currentText ?? string.Empty; useTmp = isTmp; captured = true; } private void OnEnable() { LocalizationService.EnsureInitialized(); LocalizationService.LanguageChanged += HandleLanguageChanged; _nextRefreshAt = 0f; Refresh(); } private void OnDisable() { LocalizationService.LanguageChanged -= HandleLanguageChanged; } private void LateUpdate() { if (Time.unscaledTime < _nextRefreshAt) { return; } _nextRefreshAt = Time.unscaledTime + Mathf.Max(0.05f, refreshIntervalSeconds); CaptureRuntimeChanges(); } public void Refresh() { if (!captured) { return; } string localized = LocalizationService.LocalizeLiteral(sourceText); if (useTmp) { TMP_Text tmp = GetComponent(); if (tmp != null) { tmp.text = localized; _lastAppliedText = localized; } return; } Text text = GetComponent(); if (text != null) { text.text = localized; _lastAppliedText = localized; } } private void CaptureRuntimeChanges() { string currentText = GetCurrentText(); if (string.IsNullOrEmpty(currentText)) { return; } if (!captured) { CaptureIfNeeded(currentText, GetComponent() != null); Refresh(); return; } if (currentText == _lastAppliedText) { return; } if (currentText == sourceText) { Refresh(); return; } sourceText = currentText; Refresh(); } private string GetCurrentText() { if (useTmp) { TMP_Text tmp = GetComponent(); return tmp != null ? tmp.text : null; } Text text = GetComponent(); return text != null ? text.text : null; } private void HandleLanguageChanged(string languageCode) { Refresh(); } }