- Home /
Trouble instantiating ui text
In my game, I want a box with the scores of each player to show up at the end of a level. The box is easy since I can just drag a UI Image into the scene, but because the number of players changes and I haven't decided on a maximum yet, I want to generate the text through code. I created a Text prefab and thought I had some code that would work, but the text doesn't show up on screen:
GameObject go = (GameObject)Instantiate (Resources.Load ("Prefabs/UIText"));
go.GetComponent<RectTransform> ().position = new Vector3 (Screen.width * 0.5f, Screen.height * 0.5f, 0.2f);
go.GetComponent<Text>().text = str;
The problem can't be that str is empty, because I check that it isn't with Debug.Log right before this. It can't be that it shows up behind the box, because the box is transparent. And it's definitely showing up at the right position- I checked with Debug.Log right after this code. So what's going on?
Answer by Xeong-Hu · Oct 18, 2015 at 10:57 AM
Hey dude .
i had this problem aswell.
i think what you gotta do is, make your instatiated UI object a child of your canvas. after that you can set the position to what ever you like.
so like i think
Cloned.transform.SetParent(CanvasParent.transform);
but make sure it executes first right after you instatiated your object
I Hope that fixes things
Setting the parent to the canvas solved my problem, thanks! In case anyone's wondering, I added this line of code: go.transform.SetParent(GameObject.FindGameObjectWithTag("UICanvas").transform); And tagged the canvas with UICanvas.
Nice! Totally glad to help! Good luck on your game!
Your answer
Follow this Question
Related Questions
Text UI field input doesn't get saved in my prefab 0 Answers
UI components all disappear on Play mode, then stay invisible 2 Answers
UI Text.color not assigning? 2 Answers
Display text above prefabs in Unity 4.6 0 Answers
1 UI Text vs 2 UI Text 1 Answer