Question: Finding various text components

Not sure if this is even possible but here I go.

I have various text components (TextMeshPro, buttons, ect) and I would like to find all of them on any given gameobject. Is there any way aside from trying to find each individual type of component?

What I am trying to do is find and replace the text based on a localization system we have. So we would put something like MAIN_BTN_PLAY as the default string for a component. Then at run time we would ask our localization system what string should replace MAIN_BTN_PLAY and put it in its place.

We are hoping to make it more generic. So a general component would be added to any gameObject we want localized. That object would listen for any update events and then change any needed parts, but hopefully not require knowing the specific component we are working with.

Thank you for any help or ideas anyone can give.

At some point you’re going to need to either (1) know what components to look for or (2) have references to strings that you want to localize.

For (1), you could use a facade that internally finds text components of various types that you’ve manually specified. Publicly, it provides a single interface to get & set the text regardless of the underlying text components. Something like:

public class UniversalText : MonoBehaviour {

    public string text {
        get { return GetText(); }
        set { SetText(value); }
    }

    private UnityEngine.UI.Text uiText;
    private TMPro.TextMeshPro tmpText; // etc.

    void Awake() {
        uiText = GetComponent<UnityEngine.UI.Text>();
        tmpText = GetComponent<TMPro.TextMeshPro>();
    }

    private string GetText() {
        if (uiText != null) return uiText.text;
        if (tmpText != null) return tmpText.text;
    }

    private void SetText(string value) {
        if (uiText != null) uiText.text = value;
        if (tmpText != null) tmpText.text = value;
    }
}

But (2) might be a more elegant solution. Use a UnityEvent in your localization component. Then assign whatever string variables from whatever components you want to localize. @JoeStrout did a nice tutorial called The Real Power of UnityEvent.

1 Like

After getting some help we decided on implementing a wrapper for Text and TextMeshPro which we will use and hopefully not have any issues when we need to update things. Then simply listen to a Occurance and update as needed there.

Kinda sucks that both wrappers are identicle but we need seperate ones for each text like object.

Thanks for the video link, qute interesting. I will keep that in mind for later use.