Adding a text box using c#

I’m trying to show some text in a formatted way, so I figured that the best way is to dynamically create text boxes and put them in a grid.

So my logic is that I should create a gameObject, convert it to a text object, and then add it to the parent (the object that has grid layout component).

My code is as follows:

`
using UnityEngine;
using System.Collections;
using UnityEngine.UI;

public class GridTest : MonoBehaviour {

// Use this for initialization
void Start () {
    GameObject newObject = new GameObject("myText");
    newObject.transform.parent = transform;

    Text myText = newObject.AddComponent<Text>();
    myText.text = "Hello!";
}

}
`

GridTest is a script attached to an image, where I added a grid layout component. The problem is that when I run the code, the text box doesn’t appear, I expect it to appear inside the image like when adding the text box manually as a child of the image.

Do you have a Canvas object in the scene? Are you adding the new object as a child of the Canvas?

I ended up solving it as follows:

  1. Adding a Text field for the class at the beginning: public Text t;
  2. Instantiating similar Texts using the instruction: Text t2 = Instantiate(t);
  3. Making the new Text as a child for the original’s parent: t2.transform.parent = t.transform.parent;

In case you don’t want the player to see the sample Text t, you can just put it somewhere outside the canvas.