简体   繁体   中英

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. 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!

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....

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM