How to update text that has a dynamically retrieve it localized string

Maybe the title is a little bit confusing, so I will try to explain my scene:

I’ve a button, that when it’s pressed, it performs a calculation (a login in my case), and if the calculation throw an Exception, should display a message regarding this Exception.

[SerializeField] private TMP_Text errorMessage = null;

private const string STRINGKEY_ERROR_SHORTPASSWORD = "ErrorMessage_ShortPassword";
private const string STRINGKEY_ERROR_IMPOSSIBLE = "ErrorMessage_ImpossibleToLogin";

private void OnConfirmButton()
{
    try
    {
        loginBO.Login(Username, Password);
        HideErrorMessage();
        OnLoginCompleted?.Invoke();
    }
    catch (FormatException)
    {
        DisplayErrorMessage(localizationBO.GetLocalizedString(STRINGKEY_ERROR_SHORTPASSWORD));
    }
    catch (LoginException)
    {
        DisplayErrorMessage(localizationBO.GetLocalizedString(STRINGKEY_ERROR_IMPOSSIBLE));
    }
}

private void DisplayErrorMessage(string message = "Error")
{
    errorMessage.gameObject.SetActive(true);
    errorMessage.text = message;
}
private void HideErrorMessage()
{
    errorMessage.gameObject.SetActive(false);
    errorMessage.text = string.Empty;
}

My problem is that I’m setting the text with a simple string retrieve it from my LocalizationBusinessObject which will search the key on every table, and retrieve the current located string, so far so good.

My problem starts when I change my Locale on runtime, this message won’t be update cause it’s not “subscribed” to this change, so my question is, which will be the best approach for this? I know I can subscribe to LocalizationSettings.SelectedLocaleChanged but maybe there is an easy way that I’m missing to do not have every text listening for that, any recomendation?

Thanks!

I would suggest you use the LocalizedString.
Something like this:

[SerializeField] private TMP_Text errorMessage = null;

public LocalizedString shortPasswordError = new LocalizedString("My Table", "ErrorMessage_ShortPassword");
public LocalizedString impossibleToLoginError = new LocalizedString("My Table", "ErrorMessage_ShortPassword");

private void OnConfirmButton()
{
    try
    {
        loginBO.Login(Username, Password);
        HideErrorMessage();
        OnLoginCompleted?.Invoke();
    }
    catch (FormatException)
    {
        shortPasswordError.StringChanged += DisplayErrorMessage;
    }
    catch (LoginException)
    {
        impossibleToLoginError.StringChanged += DisplayErrorMessage;
    }
}

private void DisplayErrorMessage(string message = "Error")
{
    errorMessage.gameObject.SetActive(true);
    errorMessage.text = message;
}

private void HideErrorMessage()
{
    // Clear old error messages
    shortPasswordError.StringChanged -= DisplayErrorMessage;
    impossibleToLoginError.StringChanged -= DisplayErrorMessage;

    errorMessage.gameObject.SetActive(false);
    errorMessage.text = string.Empty;
}
1 Like