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