How to know if the text has been changed?

Hello!
I want the button width to match the text width.
To do this, I need to know the preferred width of the text. Since the width of the text in different languages is different, I have to catch the moment when the text has changed, and at that moment get “text.preferredWidth” property.
Is there any event of this?
6884426--804458--2iCj03OSFq.gif

It seems “yield return LocalizationSettings.InitializationOperation” after changing the language is working as I need. But can I be sure that this means that the all texts have changed?

LocalizationSettings.SelectedLocale = LocalizationSettings.AvailableLocales.Locales[0];
yield return LocalizationSettings.InitializationOperation;
// Can I get the "preferredWidth" of the text now??? Or should I wait a little longer?
//float width = text.preferredWidth;
//Vector2 sizeDelta = buttonRectTransform.sizeDelta;
//sizeDelta.x = width;
//buttonRectTransform.sizeDelta = width;

Hi,
Take a look at the Loading Strings Samples, you can get to them in the package manager.
You can get the string in the update event, do what you need to and then pass it to the Text Component yourself.

using UnityEngine;
using UnityEngine.Localization;
using UnityEngine.UI;

public class LocalizedStringWithChangeHandlerExample : MonoBehaviour
{
    public LocalizedString stringRef = new LocalizedString() { TableReference = "My String Table", TableEntryReference = "Hello World" };
    public Text text;

    void OnEnable()
    {
        stringRef.StringChanged += UpdateString;
    }

    void OnDisable()
    {
        stringRef.StringChanged -= UpdateString;
    }

    void UpdateString(string translatedValue)
    {
        // Do something here
        text.text = translatedValue;
    }
}

Alternatively you could just add an extra event to the Localized String Event Update String callbacks. This will get called every time the value changes.

It seems I need that alternative way, because I want to make a separate component to change the width.
I do not know the events very well yet. Did I write the code correctly:

GetComponent<LocalizeStringEvent>().OnUpdateString.AddListener(TextWasChanged);

?
This is how it completely:

That looks correct. Does it work?

Yes, thank you!

1 Like