How to create a canvas and text (UI 4.6) object using c#

I’ve been through lots of tutorials about setting and updating text of objects created using the unity GUI.

However I’d like to create a new canvas’s with text, images and other sub-objects just using c#.

If possible I’d like to create these without instantiate prefabs just because I prefer doing things in code by creating an object from its components rather than creating a prefab.

EDIT: the following code works:

using UnityEngine;
using System.Collections.Generic;
using UnityEngine.UI;

public class TestScript : MonoBehaviour {

	public GameObject myGO;

	void Start () {
		myGO = new GameObject ();
		myGO.name = "TestCanvas";
		myGO.AddComponent<Canvas> ();
		Canvas myCanvas = myGO.GetComponent<Canvas> ();
		myCanvas.renderMode = RenderMode.ScreenSpaceOverlay;
		myGO.AddComponent<Text> ();
		Text textComponent = myGO.GetComponent<Text> ();
		Material newMaterialRef = Resources.Load<Material> ("3DTextCoolVetica");
		Font myFont = Resources.Load<Font> ("coolvetica rg");

		textComponent.font = myFont;
		textComponent.material = newMaterialRef;
		textComponent.text = "Hello World";
		myGO.AddComponent<Slider> ();
	}

}

I should point out for the above to work; the font and material are loaded at runtime and so therefore must be placed in the “Resources” folder, I used a font called coolveticarg in this example.

OR : to add a child object with a rect transform allows for resizing behavior.

using System.Collections.Generic;
using UnityEngine.UI;

public class TestScript : MonoBehaviour {

	private GameObject myGO;
	private GameObject childGO;

	void Start () {
		// create game object and child object
		myGO = new GameObject ();
		childGO = new GameObject ();

		// give them names for fun
		myGO.name = "TestCanvas";
		childGO.name = "ChildObject";

		// set the child object as a child of the parent
		childGO.transform.parent = myGO.transform;

		// add a canvas to the parent
		myGO.AddComponent<Canvas> ();
		// add a recttransform to the child
		childGO.AddComponent<RectTransform> ();

		// make a reference to the parent canvas and use the ref to set its properties
		Canvas myCanvas = myGO.GetComponent<Canvas> ();
		myCanvas.renderMode = RenderMode.ScreenSpaceOverlay;


		// add a text component to the child
		childGO.AddComponent<Text> ();
		// make a reference to the child rect transform and set its values
		RectTransform childRectTransform = childGO.GetComponent<RectTransform> ();
		RectTransform parentRectTransform = myGO.GetComponent<RectTransform> ();

		// set child anchors for resizing behaviour
		childRectTransform.anchoredPosition3D = new Vector3(0f,0f,0f);
		childRectTransform.sizeDelta = new Vector2 (0f, 0f);
		childRectTransform.anchorMin = new Vector2 (0f,0f);
		childRectTransform.anchorMax = new Vector2 (1f, 1f);

		// set text font type and material at runtime from font stored in Resources folder
		Text textComponent = childGO.GetComponent<Text> ();
		Material newMaterialRef = Resources.Load<Material> ("3DTextCoolVetica");
		Font myFont = Resources.Load<Font> ("coolvetica rg");

		textComponent.font = myFont;
		textComponent.material = newMaterialRef;

		// set the font text
		textComponent.text = "Hello World";

	}

GameObject g = new GameObject();
Canvas canvas = g.AddComponent();
canvas.renderMode = RenderMode.WorldSpace;
CanvasScaler cs = g.AddComponent();
cs.scaleFactor = 10.0f;
cs.dynamicPixelsPerUnit = 10f;
GraphicRaycaster gr = g.AddComponent();
g.GetComponent().SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, 3.0f);
g.GetComponent().SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, 3.0f);
GameObject g2 = new GameObject();
g2.name = “Text”;
g2.transform.parent = g.transform;
Text t = g2.AddComponent();
g2.GetComponent().SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, 3.0f);
g2.GetComponent().SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, 3.0f);
t.alignment = TextAnchor.MiddleCenter;
t.horizontalOverflow = HorizontalWrapMode.Overflow;
t.verticalOverflow = VerticalWrapMode.Overflow;
Font ArialFont = (Font)Resources.GetBuiltinResource (typeof(Font), “Arial.ttf”);
t.font = ArialFont;
t.fontSize = 7;
t.text = “Test”;
t.enabled = true;
t.color = Color.black;

            g.name = "Text Label";
            bool bWorldPosition = false;

			g.GetComponent<RectTransform>().SetParent(this.transform, bWorldPosition);
            g.transform.localPosition = new Vector3(0f, fTextLabelHeight, 0f);
            g.transform.localScale = new Vector3( 
                                                 1.0f / this.transform.localScale.x * 0.1f,
                                                 1.0f / this.transform.localScale.y * 0.1f, 
                                                 1.0f / this.transform.localScale.z * 0.1f );

This is relatively simple. Just create an empty GameObject and call AddComponent until you have everything you need. Be sure to create an Event System as well.

To find out all the components simply make the GameObjects you require in the scene view. Then copy off the components to code.

Note: I’ve found the best way is to create prefab ‘pieces’ then link them together via code. There are various tutorials on this approach linked on my profile page.