Creating 3d text in C# script, object spawns but I can't set font

I’m trying to create several text objects to display numbers for an animation. This is my code so far:

Font ArialFont = (Font)Resources.GetBuiltinResource(typeof(Font), "Arial.ttf");
	
GameObject myTextObject = new GameObject("test");
myTextObject.AddComponent("TextMesh");
myTextObject.AddComponent("MeshRenderer");

TextMesh textMeshComponent = myTextObject.GetComponent(typeof(TextMesh)) as TextMesh;
MeshRenderer meshRendererComponent = myTextObject.GetComponent(typeof(MeshRenderer)) as MeshRenderer;

textMeshComponent.font = ArialFont;
textMeshComponent.text = "im alive";

I’m able to create the text object, but the text appears as a pink block. I created 3d text using the editor to trouble the shoot. The only difference between text objects created in the script and editor is in the MeshRenderer portion of the inspector. Under the materials field, subfield Element 0 the scripted object has nothing while the object created in the editor says “Font Material”.

Can someone direct me as to how I can fix my code?

You need to set the renderer.material to use the correct material. TextMesh.font is really only for the font metrics; you need a material so it can use the appropriate texture and shader.

–Eric

I’ve only worked with cubes, spheres, planes etc, so forgive my inexperience. So you’re saying I need to set the material of my text object with:

textMeshComponent.renderer.material = Resources.Load ("Arial");

Except I need to find the location of the Arial font’s material?

Almost but not quite; the renderer component is for the GameObject that the text mesh component is attached to, not the text mesh component. So, myTextObject rather than textMeshComponent.

–Eric