如何在Unity中使用UI.Text作为预制件?

时间:2016-01-02 04:45:21

标签: c# unity3d scripting unity3d-gui

我已尝试使用此

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

它成功创建了对象,如我的层次结构中所示。但即使有分配给它的文本,我也无法在屏幕上看到该文本。我只能在屏幕上看到一个空的游戏对象。

这些屏幕截图显示正在播放的游戏,所选对象是通过脚本实例化的对象。

enter image description here

enter image description here

当我拖动预制件时,它不会在场景中显示任何内容。这种情况发生在我所有的预制件上。以下是其组成部分:

enter image description here

3 个答案:

答案 0 :(得分:2)

他们需要成为Canvas的孩子,才能显示它们。

 // find canvas
GameObject canvas = GameObject.Find("Canvas");
// clone your prefab
GameObject text = Instantiate(entry, new Vector3(x, y, 0), Quaternion.identity);
// set canvas as parent to the text
text.transform.SetParent(canvas.transform);

答案 1 :(得分:2)

在新的Unity3D UI系统中,屏幕上将呈现渲染器的每个UITextButtonPanel等)组件必须具有父级Canvas组件。 实际上,您确实在项目中使用了这种方法,其中ToolbarList等父母称为Canvas,我认为其中附加了Canvas个组件。

您需要做的是将实例化的gameObject移动为拥有gameObject组件的其他Canvas的孩子。 由于Canvas类型可能有多个组件,我建议为Script中的实例化对象添加 root 的可能性。

脚本:

//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)
}

答案 2 :(得分:0)

对于每个实例,您可能必须手动启用guiTexture。