Search code examples
c#unity-game-enginemrtktextmeshpro

How to get a TextMeshProUGUI component from an instantiated/cloned gameobject?


A picture from Hierarchy :

Hierarchy

I instantiate the SlateUGUI prefab and then later tried to access the highlitged gameobject 'TextDebug' using :

 TextMeshProUGUI text1 = SlateInstant.transform.Find("TextDebug").GetComponent<TextMeshProUGUI>();
 text1.text = "This works";

However, it does not work : Error : NullReferenceException: Object reference not set to an instance of an object

I am a bit skeptical to use GetComponentInChildren<>() as it can be seen from the hierarchy it is quite a lot of children and sub-children.


Solution

  • From the Transform.Find API

    Note: Find does not perform a recursive descend down a Transform hierarchy.

    This means: It only find first level childs!

    You would need to provide the entire path starting from the first direct child like e.g.

    TextMeshProUGUI text1 = SlateInstant.transform.Find("Scroll View/Viewport/Content/GridLayout1/Column2/TextDebug").GetComponent<TextMeshProUGUI>();
    text1.text = "This works";
    

    Way better would be to have a certain controller component on the most top parent (root) of the prefab and there have a field like e.g.

    public class SlateController : MonoBehaviour
    {
        public TextMeshProUGUI TextDebug;
    }
    

    and in the prefab edit mode drag and drop the TextDebug object into that slot in the Inspector.

    And then simply use e.g.

    SlateInstant.GetComponent<TheControllerClass>().TextDebug.text = "XYZ";