TextMeshPro issues

In each scene I have two TextMeshPro components, I change one of them using this code:

private TMPro.TextMeshProUGUI _textMeshProKeyPressed;
    void Start()
    {
        _textMeshProKeyPressed = FindObjectOfType<TextMeshProUGUI>();
    }

    // Update is called once per frame
    void Update()
    {
        _textMeshProKeyPressed.SetText("Level " + level.ToString());

    }

Let’s say my first TextMeshPro object is a and my second is b. In each scene I want a to be changed. In the first scene a changes, then in the second and third b changes. How can I make it consistent/specify the name of the object I want changed?

Best way to have the right thing to happend would be to serialize your TMP text. Then you can assign it directly in the unity editor as if it was public. You then just drag and drop the right gameobject with the TMP component you want to be edit and you will be fine.

     [SerializeField]
     private TMPro.TextMeshProUGUI _textMeshProKeyPressed;
     void Start()
     {
         _textMeshProKeyPressed = FindObjectOfType<TextMeshProUGUI>();
     }
 
     // Update is called once per frame
     void Update()
     {
         _textMeshProKeyPressed.SetText("Level " + level.ToString());
 
     }

I believe that FindObjectOfType will always returns the first object in the scene’s objects hierarchy.

There should be a method FindObjectsOfType that would return all of them in an array. You number 2, so check if the array size is at least 2 and take the object at index 1.

FindObjectOfType is probably super slow and not the recommended way, but if you’re using it in Start and only a few objects in the scene do that, it’s not big deal.

The recommended way of solving this is to add the attribute [SerializeField] on the line above private TMPro.TextMeshProUGUI _textMeshProKeyPressed;

This will make the private variable editable in the Unity Editor. Just drag&drop you TextMeshPro A or B from the scene hierarchy to the field in the inspector, then you don’t need the FindObjectOfType.