首页 > 解决方案 > Unity UI 获取组件

问题描述

我正在制作一个对话系统,所以我创建了一个预制件:主角肖像(图像),NPC肖像(图像),文本将出现的图像,最后一个是文本。在我的脚本中,我传递了这个预制件并将其保存在一个名为 dialog_panel 的变量中。一旦我在代码中创建了预制件,我想更改第一个短语的文本是我的 NPC。但它崩溃了:

“GetComponent 要求请求的组件‘TextElement’来自 MonoBehaviour 或 Component 或者是一个接口。UnityEngine.GameObject.GetComponent[T] () (在 C:/buildslave/unity/build/Runtime/Export/Scripting/GameObject.bindings .cs:28) Interactivity.Update () (在 Assets/Scripts/Interactivity.cs:74)"

我尝试了一切来获取我的 UI 文本/标签的组件文本,但这是不可能的 D:。我的统一版本是:2019.3.0.a5

这是我的代码,注释的东西给了我同样的错误:

dialog_panel = Instantiate(copy_panel);
dialog_panel.transform.SetParent(FindObjectOfType<Canvas>().transform, false);
dialog_panel.transform.position = new Vector3(512, 99, dialog_panel.transform.position.z);
//dialog_panel.transform.Find("Text").GetComponent<Label>().text = "HOLAA";
/*GameObject obj = GameObject.Find("NPCText");
TextElement instruction = obj.GetComponent<TextElement>();
instruction.text = "HI";
//obj.GetComponent<TextElement>().text = "HI";*/
// dialog_panel.transform.Find("Text").GetComponent<Label>().text = "HI"; 
dialog_panel.transform.Find("Text").GetComponent<TextElement>().text = "HI";

标签: c#user-interfaceunity3d

解决方案


推荐阅读