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

How to do it...

To create an interactive text input box to the user, follow these steps:

  1. Create a new Unity 2D project.
  2. In the Inspector, change the background of the Main Camera to solid white.
  1. Add a UI Input Field to the Scene. Position this to the top-center of the screen.
  2. Add a UI Text GameObject to the scene, naming it Text-prompt. Position this to the left of Input Field. Change the Text property of this GameObject to Name:.
  3. Create a new UI Text GameObject named Text-display. Position this to the right of the Input Text control, and color its text red.
  4. Delete all of the content of the Text property of this new GameObject (so initially the user won't see any text on screen for this GameObject).
  5. Add an instance of the DisplayChangedTextContent C# script class to the Text-display GameObject:
using UnityEngine; 
using UnityEngine.UI; 

public class DisplayChangedTextContent : MonoBehaviour { 
   public InputField inputField; 
   private Text textDisplay; 

   void Awake() { 
         textDisplay = GetComponent<Text>(); 
   } 

   public void DisplayNewValue () { 
         textDisplay.text = "last entry = '" + inputField.text + "'"; 
   } 
} 
  1. With Text-display selected in the Hierarchy, from the Project panel drag the Input Field GameObject into the public Input Field variable of the Display Changed Content (Script) component:
  1. With Input Field selected in the Hierarchy, add an End Edit (String) event to the list of event handlers for the Input Field (Script) component. Click on the plus (+) button to add an event-handler slot, and drag the Text-display GameObject into the Object slot.
  2. From the Function drop-down menu, choose DisplayChangedTextContent and then choose the DisplayNewValue method.
  3. Save and run the Scene. Each time the user types in new text and then presses Tab or Enter, the End Edit event will fire, and you'll see a new content text message displayed in red on the screen.