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

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!