- Home /
How to use inputfield with a button and text?
I want to get text from an InputField and when I press a button, display it in the UI Text box.
I have seen this unanswered question so many places, and I finally have the answer. I made the question simpler than my original one to make it all clear.
I've gone through those. They give an overview of what the components are but don't talk at all about how to use them with each other. Do you know where I can find that kind of information?
Answer by DiegoSLTS · Mar 20, 2015 at 01:30 PM
It's pretty easy, you need a script that has a reference to the InputField and the Text, and a function that takes the text from the input and set it as the text of the Text when called. Then, setup that function to be called when the button is pressed.
The script should look similar to this: using UnityEngine; using UnityEngine.UI;
public class InputFieldToText : MonoBehaviour {
public InputField Field;
public Text TextBox;
public void CopyText() {
TextBox.text = Field.text;
}
}
Now:
Create a Button, an InputField and a Text
Add that InputFieldToText script to any object, select that object and drag and drop the InputField and the Text in the proper slots for that script.
Select the Button and look at the inspector, there's a Box at the bottom to add functions that should be called when the button is clicked.
Press the "+" button at the bottom right of that box, it'll add a new line.
Drag and drop the game object that has the InputFieldToText component into the box where it says "(None) Object", it will enable the drop down button next to it.
Click in that dropdown, look for the InputFieldToText entry in that list and select it.
It will display another menu with valid functions you can call from that script, select the CopyText function.
That's it, run the game, type some text in the input field and press the button.
Also, if you can't find tutorials explaining how to use something there's always the API documentation. You can see there that the InputField and the Text classes both have a "text" property.
It works. Thank you so much for taking the time to answer. The documentation is slowly making sense :).