Home > Software design >  How to get TextMeshProUGUI component from an instantiated/cloned Slate gameobject?
How to get TextMeshProUGUI component from an instantiated/cloned Slate gameobject?

Time:09-28

I want to access TextMeshPro-Text(UI) component as shown in the pic which is on a SlateUGUI gameobject(clone) provided by MRTK :

 TextMeshPro-Text(UI)

The Hierarchy looks like this :

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.

How to solve this in a simpler way? What am I doing wrong?

CodePudding user response:

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";
  • Related