- Home /
Unity4.6 - Setting text Property on Text Object
Hi,
I'm new to uGUI in 4.6 and I'm hitting a peculiar issue after instantiating a gameObject from a prefab. I have a prefab which is an empty GameObject with a Text object underneath it, hierarchy as follows;
GameObject
Text (uGUI)
The intent is that I can instantiate a number of these objects in specific areas of the worldspace such that I can have floating labels around the world. The world is made up of a particle system and it is individual particles I'm trying to label, in this case each one representing a vessel at sea.
This is the code that I'm having issues with;
if (visibleVessels.Count > 0)
{
// for each vessel, create a label
GameObject[] labels = new GameObject[visibleVessels.Count];
for (int i = 0; i < visibleVessels.Count; i++)
{
labels[i] = (GameObject)Instantiate(vesselLabel);
labels[i].transform.position = GenPosition(visibleVessels[i], worldFlat, globalOffset);
labels[i].transform.SetParent(labelCanvas.transform, true);
labels[i].GetComponent<Text>().text = visibleVessels[i].Name.ToString();
}
}
visibleVessels is a list of positions, I get the correct number of labels on the screen however then I try to set the text value I get "Object reference not set to an instance of an object.
Is there a new way to address components I've missed or am I barking up the wrong tree?
Any pointers would be greatly received.
Regards, Keegan
Answer by troien · Nov 10, 2014 at 11:10 AM
Well, assuming that with the following line
labels[i] = (GameObject)Instantiate(vesselLabel);
You instantiate this prefab you described which is a GameObject with a Text component on his child.
Then you should change this
labels[i].GetComponent<Text>().text
To this
labels[i].GetComponentInChildren<Text>().text
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
4.6 .interactable not working 1 Answer
Illuminating a 3D object's edges OnMouseOver (script in c#)? 1 Answer
Unable to click UI Button (Unity 4.6) when TimeScale is 0 1 Answer