Unity 2018 Cookbook(Third Edition)
上QQ阅读APP看书,第一时间看更新

How it works...

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 (as do Buttons) include a default rounded rectangle image, with a white background.

There are usually three Text GameObjects involved with the user text input:

  • The static prompt text, in our recipe, displaying to the user 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) that is actually displayed to the user, showing the characters as they type.

You created an Input Field 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 text 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 red fourth Text GameObject Text-display, to confirm to the user what they last entered in the Input Field. You created the DisplayChangedTextContent C# script class, and added an instance as a component of the Text-display GameObject. You linked the Input Field GameObject to the Input Field public variable of the scripted component (so the script can access the text content entered by the user).

You registered an End Edit event handler of the 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.