Reputation: 103
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. I assumed GetComponents would get all input fields in the scene and save them to an array. Then I could cycle through each index and get the text property of each input. Is this incorrect?
Thanks!
Upvotes: 1
Views: 2766
Reputation: 490
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...
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:
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....
Upvotes: 2