How to use UI.Text as a prefab in Unity?

jeanl picture jeanl · Jan 2, 2016 · Viewed 9.5k times · Source

I've tried using this

Instantiate(entry, new Vector3(x, y, 0), Quaternion.identity);

It successfully created objects, as seen in my hierarchy. But I cannot see the text on the screen, even though there is a text assigned to it. I can only see an empty game object on the screen.

These screenshots show the game on play, and the selected object is the object instantiated through the script.

enter image description here

enter image description here

When I drag the prefab, it does not show anything on the scene. This happens to all my prefabs. The following are its components:

enter image description here

Answer

mwilczynski picture mwilczynski · Jan 2, 2016

In new Unity3D UI system, every UI (Text, Button, Panel etc.) component that will be renderer on screen must have a parent Canvas component. You actually do use such approach in your project, where you have Toolbar, List etc. that have parent called Canvas and which I suppose has Canvas component attached.

What you need to do is to move instantiated gameObject to be child of other gameObject that holds Canvas component. As there can be multiple components of Canvas type, I would suggest to add possibility to assign root for instantiated objects inside your Script.

Script:

//Drag and drop this from inspector; make sure that dragged gameObject
//has Canvas component in it or above it (in parent)
public Transform EntriesRoot;

void Start()
{
    var entry = Instantiate(entry, new Vector3(x, y, 0), Quaternion.identity);
    //Put parent to our EntriesRoot
    //EntriesRoot will be our new parent for entry in hierarchy
    entry.transform.SetParent(EntriesRoot)
}