Dynamically added UI text is not displaying

The UI text that I’ve added is not rendering on my screen, and I cannot figure out why.

I followed the exact same steps as I’m using to dynamically add a UI image.

In the scene at run time, the RectTransform appears where it should (in the middle of the screen canvas) - but the text that it says has been set in the inspector is not showing.

Here is my code:

private Text SetHealthUiText(Canvas canvas)
{
    var uiObject = new GameObject(Unit.Name + "HealthUi");

    var rectTransform = uiObject.AddComponent<RectTransform>();

    rectTransform.SetParent(canvas.transform);

    rectTransform.localScale = Vector3.one;

    rectTransform.localPosition = Vector3.zero;

    rectTransform.position = Vector3.zero;

    rectTransform.anchoredPosition = Vector2.zero;

    rectTransform.sizeDelta = new Vector2(50, 50);

    var text = uiObject.AddComponent<Text>();

    text.font = new Font("Arial");

    text.fontSize = 14;

    text.color = Color.black;

    text.text = "0";

    return text;
}

What am I missing?

@lnwhitling, If you see the text you set in the inspector and you are satisfied it is in the location where you should see it, but it does not show on the screen, then it could be the width and height of the Text element is not big enough.

Try increase the width to like 200 and maybe the height. You can fiddle with those values in the inspector while the game is running to find the right values. (or any of the other values if changing the size doesn’t fix it. )

Ok - I finally got to the bottom of this.

Specifying the font is necessary - and of course I was doing that incorrectly.

The fault in my code was:
text.font = new Font(“Arial”);

It should have been:
text.font = (Font)Resources.GetBuiltinResource(typeof(Font), “Arial.ttf”);

In the inspector, when I paused the scene, it showed Arial as being the font, so I assumed that this wasn’t a problem. Egg on my face.