Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/313.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 在unity中,如何访问作为对象子对象的文本?_C#_Unity3d - Fatal编程技术网

C# 在unity中,如何访问作为对象子对象的文本?

C# 在unity中,如何访问作为对象子对象的文本?,c#,unity3d,C#,Unity3d,我试图访问一个点击按钮的文本。但是ıt总是返回gameObject的第一个子项的文本。但是我想访问点击子项的文本 我尝试了下面的代码: transform.gameObject.GetComponentInChildren<Button>().GetComponentInChildren<Text>().text; 您可以创建一个自定义类,该类引用您关心的文本: 公共类ButtonExtras:单一行为 { public Text buttonText;//在检查器中分

我试图访问一个点击按钮的文本。但是ıt总是返回gameObject的第一个子项的文本。但是我想访问点击子项的文本

我尝试了下面的代码:

transform.gameObject.GetComponentInChildren<Button>().GetComponentInChildren<Text>().text;

您可以创建一个自定义类,该类引用您关心的文本:

公共类ButtonExtras:单一行为 { public Text buttonText;//在检查器中分配此 } 然后在其他地方:

getComponentChildren.buttonText.text=hello!;
因此,我假设您显示的代码行位于某个常规对象上的脚本中,而不是位于每个按钮上。因此,您可以将按钮作为参数,如下所示:

void HandleText(Button button){
    Text text = button.getComponentInChildren<Text>();
    // do whatever you want to do with the text here
}

然后,对于每个按钮,您可以将此方法添加到OnClick listernes,并将按钮本身作为参数。希望有意义

我找到了一个简单的解决方案:

GameObject.Find(EventSystem.current.currentSelectedGameObject.name).GetComponent<Button>().GetComponentInChildren<Text>().text 

谢谢大家分享他们的想法。

您能给我们看一下完整的代码吗?如何检测单击?您的问题似乎是GetComponentChildren还搜索该游戏对象本身上的组件,而不仅仅是子组件