Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Unity 5.x Cookbook

You're reading from   Unity 5.x Cookbook More than 100 solutions to build amazing 2D and 3D games with Unity

Arrow left icon
Product type Paperback
Published in Oct 2015
Publisher Packt
ISBN-13 9781784391362
Length 570 pages
Edition 1st Edition
Languages
Tools
Arrow right icon
Toc

Table of Contents (14) Chapters Close

Preface 1. Core UI – Messages, Menus, Scores, and Timers 2. Inventory GUIs FREE CHAPTER 3. 2D Animation 4. Creating Maps and Materials 5. Using Cameras 6. Lights and Effects 7. Controlling 3D Animations 8. Positions, Movement and Navigation for Character GameObjects 9. Playing and Manipulating Sounds 10. Working with External Resource Files and Devices 11. Improving Games with Extra Features and Optimization 12. Editor Extensions Index

Input Fields component for text entry

While many times we just wish to display non-interactive text messages to the user, there are times (such as name entry for high scores) where we wish that the user was able to enter text or numbers into our game. Unity provides the Input Field UI component for this purpose. In this recipe, we'll create a simple text input UI by making use of the default Button image and text GameObjects, and we'll add a script to respond to each new value of the input field.

Note

You can, of course, create a working text input quicker than this recipe's method by choosing menu: Create | UI | Input Field, which creates a GameObject containing an Input Field component, child text, and placeholder GameObjects, as shown in the following screenshot. However, by following the steps in this recipe, you'll learn the interrelationships between the different interface elements, because you'll be creating these connections manually from the deconstructed parts of the UI Button GameObject.

Input Fields component for text entry

How to do it...

To create a promoted text input box to the user with faint placeholder text, follow these steps:

  1. Create a new Unity 2D project.
  2. In the Inspector view, change the background of the Main Camera to solid white.
  3. Add a UI Button to the scene. Delete the Button (Script) component of the Button GameObject (since it won't be a button, it will be an interactive text input by the time we are finished with it!).
  4. Rename the Text child GameObject of the Button component to Text-placeholder. Uncheck the Rich Text option, change the text to Enter name…, change the Alignment in Left and Top, and in the Rect Transform, set Left to 4 and Top to 7.
    How to do it...
  5. Duplicate Text-placeholder by naming the copy Text-prompt. Change the Text of this GameObject to Name:, and set its Left position to -50.
  6. Duplicate Text-placeholder again, naming this new copy Text-input. Delete all of the content of the Text property of this new GameObject.
  7. Select Text-placeholder in the Hierarchy, and we will now make the placeholder text mostly transparent. Set the A (alpha) Color value of the Text (Script) component of this GameObject to a value that is about a quarter of its maximum value (e.g. 64).
  8. Select Text-input in the Hierarchy, and add an Input Field component by choosing menu: Add Component | UI | Input Field.
  9. Drag the Text-input GameObject into the Text Component property of Input Field, and drag the Text-placeholder GameObject into the Placeholder property.
  10. Save and run your scene. You now have a working text input UI for your user. 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.

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, we have made use of the default rounded rectangle image that Unity provides when a Button GameObject is created. Buttons have both an Image component and a Text child GameObject. So, two items that we need can be acquired very easily by creating a new Button, and simply by removing the Button (Script) component.

There are usually three Text GameObjects involved with the user text input: the static prompt text (in our recipe, for example, the Name: text); then the faint placeholder text, reminding users where and what they should type; and finally the text object (with the font and color settings and so on) that is actually displayed to the user, showing the characters as they type.

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. Note that the Content Type of the Input Field (Script), in the Inspector, can be set to several specific types of text input, including e-mail addresses, integer or decimal numbers only, or the password text (where an asterisk is displayed for each entered character).

There's more...

There are some details that you don't want to miss.

Executing a C# method to respond each time the user changes the input text content

Having interactive text on the screen isn't of much use unless we can retrieve the text entered to use in our game logic, and we may need to know each time the user changes the text content and act accordingly.

To add code and events to respond each time the text content has been changed by the user, do the following:

  1. Add an instance of the C# script class called DisplayChangedTextContent to the Text-input GameObject:
    using UnityEngine;
    using System.Collections;
    using UnityEngine.UI;
    
    public class DisplayChangedTextContent : MonoBehaviour {
      private InputField inputField;
    
      void Start(){
        inputField = GetComponent<InputField>();
      }
    
      public void PrintNewValue (){
        string msg = "new content = '" + inputField.text + "'";
        print (msg);
    }
    }
  2. 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-input GameObject into the Object slot.
  3. From the Function drop-down menu, choose DisplayChangedTextContent and then choose the PrintNewValue method.
  4. 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 printed in the Console window by our script, as shown in the following screenshot:
    Executing a C# method to respond each time the user changes the input text content
lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image