[英]How would I go about getting the text from all input fields in a scene in Unity 5?
As of right now, I have two input fields and a button in my scene. 截至目前,我的场景中有两个输入字段和一个按钮。 When the button is clicked, I would like to retrieve the contents of both input fields.
单击按钮后,我想检索两个输入字段的内容。 I can get the contents of each one separately by adding the same script twice on the on click function of them button.
通过在它们的按钮功能上添加两次相同的脚本,我可以分别获取每个内容。 However, I want to get both input fields while only using one script.
但是,我只想使用一个脚本就获得两个输入字段。
I've tried using GetComponents, bu I guess I'm not understanding how it works. 我试过使用GetComponents,但是我想我不明白它是如何工作的。 I assumed GetComponents would get all input fields in the scene and save them to an array.
我假设GetComponents将获取场景中的所有输入字段并将其保存到数组中。 Then I could cycle through each index and get the text property of each input.
然后,我可以循环浏览每个索引并获取每个输入的text属性。 Is this incorrect?
这不正确吗?
Thanks! 谢谢!
what you can do is use GetComponentsInChildren... put all your GameObjects with a component InputField inside a Parent Game Object, then add your script to the parent... 您可以做的是使用GetComponentsInChildren ...,将所有带有GameInput对象的GameObjects都放置在Parent Game Object中,然后将脚本添加到Parent ...
then do something like: 然后做类似的事情:
---Edit: Ok I played a little with the Inputfields... so if you pay attention, your inputfield has 2 children objects, one called "Placeholder" and another one called "Text" and both of them have a Text component, so what you have to do is something like: ---编辑:好吧,我在Inputfields上玩了一点...所以,如果您注意的话,您的inputfield有2个子对象,一个称为“占位符”,另一个称为“文本”,并且它们都有一个Text组件,所以您要做的是:
List<string> textFromMyInputs = new List<string>();
void GetAllTextFromInputFields()
{
foreach(InputField inputField in gameObject.GetComponentsInChildren<InputField>())
{
foreach (Text text in inputField.GetComponentsInChildren<Text>())
{
if (text.gameObject.name != "Placeholder")
textFromMyInputs.Add(text.text);
}
}
foreach (string s in textFromMyInputs)
{
Debug.Log(s);
}
}
Already tested and it's working for me.... 已经过测试,对我有用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.