- Home /
setting the text of an instantiated prefab's child's guitext object
Hi - i'm instantiating a prefab at runtime, and trying to set the gui text of a nested gameobject, but my syntax isn't working. This is my code:
var scoreBoard = Instantiate(scoreBoard, Vector3 (0, 0, 0), Quaternion.identity);
var yourScore = transform.Find("YourScore"); //YourScore is a child of scoreBoard.
yourScore.GetComponent(GUIText).text = userScore; //yourScore has a GUIText attached to it, and userScore is a stored String.
how do I do this properly?
It is a bit odd that the variable you are Instantiating is the same name as the one you're then assigning to. I presume there is a class member called scoreBoard that you are dragging a prefab to.
Answer by Waz · Jul 28, 2011 at 10:11 PM
Seems you mean:
var yourScore = scoreBoard.transform.Find("YourScore"); //YourScore is a child of scoreBoard
thanks - that worked. Revised code as follows:
var scoreBoard = Instantiate(scoreBoard, Vector3 (0, 0, 0), Quaternion.identity); var playerScore = scoreBoard.transform.Find("YourScore"); playerScore.guiText.text = scoreTextRef.text;
While this is correct, it's bad form to use the same name for your new local variable as the name of the member variable, so either name the member to eg. scoreBoardPrefab or the new local variable to eg. scoreBoardInstance.