The core of interactive text input in Unity is the responsibility of the Input Field component. This needs a reference to a UI Text GameObject. To make it easier to see where the text can be typed, Text Input (similar to buttons) includes a default rounded rectangle image with a white background.
There are usually three Text GameObjects involved in user text input:
- The static prompt text, which, in our recipe, displays the text Name:.
- The faint placeholder text, reminding users where and what they should type.
- The editable text object (with the font and color settings) is actually displayed to the user, showing the characters as they type.
First, you created an InputField GameObject, which automatically provides two-child Text GameObjects, named Placeholder and Text. These represent the faint placeholder text and the editable text, which you renamed Text-input. You then added a third Text GameObject, Text-prompt, containing Name:.
The built-in scripting that is part of Input Field components does lots of work for us. At runtime, a Text-Input Input Caret GameObject is created, displaying the blinking vertical line to inform the user where their next letter will be typed. When there is no text content, the faint placeholder text will be displayed. As soon as any characters have been typed, the placeholder will be hidden and the characters typed will appear in black text. Then, if all the characters are deleted, the placeholder will appear again.
You then added a fourth Text GameObject called Text-display and made it red to tell the user what they last entered in Input Field. You created the DisplayChangedTextContent C# script class and added an instance as a component of the Text-display GameObject. You linked the InputField GameObject to the Input Field public variable of the scripted component (so that the script can access the text content entered by the user).
Finally, you registered an End Edit event handler of Input Field so that each time the user finished editing text (by pressing Enter), the DisplayNewValue() method of your DisplayChangedTextContent scripted object is invoked (executed), and the red text content of Text-display updated to tell the user what the newly edited text contained.