- Home /
Text doesn't appear when i add it via script
Hey !
My work is very simple : I want to create a score text wich will change during my game. But when I add the text via a c# script, the text doesn't appear (the gameObject is here, just the text isn't). In the inspector, the text appear, but not in the scene.
When i have a text already in my scene, it's appear
GameObject score = new GameObject("Score");
score.transform.SetParent(gameObject.transform);
RectTransform rt = score.GetComponent<RectTransform>();
rt.sizeDelta = new Vector2(150, 50);
rt.anchoredPosition = new Vector2(0, 0);
score.AddComponent<Text>().text = "Score = 0";
PS : i'm working on a UI element
Answer by MacDx · Aug 29, 2018 at 04:26 PM
I think the problem is that UI components like Text, need to be attached to a game object that has a RectTransform instead of a regular Transform in order to render. Calling new GameObject() like that will create a game object with a regular transform so that won't work.
Try this instead
GameObject score = new GameObject("Score", typeof(RectTransform));
This should create a GO with the right transform.
Don't forget that game objects with UI components need to be children of a Canvas object. If the parent of this new GO isn't part of a hierarchy where a Canvas is at the top, it won't work.
Note: Also check things like font size, color and such to see if the text is just hidden.
Hope this helps!
No, it's not working either :/
Yes, the text is children of a canvas, and the parent is the canvas itself I didn't put size, color, font, etc... in the script, but i put pause and change the values, it change nothing. The gameObject with the text composant is here, I can see the text in the text section (it's "Score = 0" as expected) but I can't see it in the scene
Color's alpha is not 0 right? If you could post a screenshot or give some more info about the setup, it would help find the problem
There's the issue! No font assigned, also, you won't see white text on a white background
Updated with a picture (there is no font, but if i add one, it change nothing)
So, you put a font and also changed the color to something other than white and it still didn't work?