How to preserve sprites in TMP text component?

Recently I have started looking into the official Localization package and started converting standalone texts to being localized which works like a charm. However, I have a couple of Text (UI) components in which I am using the sprite tag to add images to buttons.

8718993--1178790--upload_2023-1-10_10-44-9.png

8718993--1178784--upload_2023-1-10_10-43-31.png

Now obviously I could make the tag part of the translation string but I would like to avoid keeping redunant information around, considering I might want to change the sprite further down the road. What would be the recommenced approach if I wanted to have the text translated but the sprite tag preserved at the same time?

Hmm. If the issue is that you want to be able to easily change the sprite, e.g the index then you could make it a smart string and place the index as a persistent variable like so:

“<sprite={spriteId}> Upgrade”
8719017--1178802--sprite.png

This does mean you keep the sprite in the localized string though. An alternative would be to write a script that adds the sprite on before displaying it. Something like:

public class SpriteExample : MonoBehaviour
{
    public LocalizedString localizedString;
    public string spriteString = "<sprite=32>";
    public TMP_Text tMP_Text;

    void OnEnable()
    {
        localizedString.StringChanged += LocalizedString_StringChanged;
    }

    void OnDisable()
    {
        localizedString.StringChanged -= LocalizedString_StringChanged;
    }

    void LocalizedString_StringChanged(string value)
    {
        tMP_Text.text = $"{spriteString} {value}";
    }
}
1 Like

The second option sounds more helpful in that case - it’s a bit of extra work but at least nobody needs to worry about the sprite tag in the translation table. :smile:

1 Like