0

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.

holouser
  • 172
  • 11

2 Answers2

2

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";
derHugo
  • 83,094
  • 9
  • 75
  • 115
1

I think an easy solution would be to add a tag to the instantiated object and then use the FindWithTag

Kuruchy
  • 1,330
  • 1
  • 14
  • 26