Unity3D – Tutorials – UI – Input Field – JS

The new UI system give us a new Input Field, in this tutorials we are going to create a responsive ‘Input Field’ in the middle of the screen, get the user input and render it over a label.

Create a scene with:

– Main Camera

– Canvas
-> InputField
->> Placeholder
->> Text (the text of InputField)
-> Text (a label)

– EventSystem

– GameControl (Empty)

Hierarchy> Canvas> Inspector> Canvas Scaler (Script):
– Reference Resolution: X=800 Y=600
– Screen Marìtch Mode: Match Width Or Height

Hierarchy> InputField> Inspector
> Rect Transform
– Pos X=0 Y=0 Z=0
– Width= 200 Height=30
> Input Field (Script)
– Character Limit = 10 (max 10 characters allowed)

Hierarchy> InputField> Placeholder> Inspector
> Text (Script)
– Text= ‘Enter your name…, max 10 characters’

Hierchy> Text (a label)> Inspector
> Rect Transform>
– Pos X=0 Y=0 Z=0
– Width= 100 Height=100

> Text (Script)
– Text= ‘Your name here’

Now we will see in the middle of the screen:

Your name here -> (label)
|Enter your name…, max 10 characters | -> (Input Field)

Attach to GameController gameobject GameControllerScript.js:


#pragma strict
 
var MyInputField : UI.InputField; // ASSIGN IN INSPECTOR the InputField 
var TextGetInputField : UI.Text; // ASSIGN IN INSPECTOR the text of InputField
var TextLabel: UI.Text; // ASSIGN IN INSPECTOR the text of the label
 
function Awake () {
}// END Awake()
 
function Start () {
        // Focus on InputField if doesn't make sense to force the user to click on it.
	MyInputField.ActivateInputField();
	MyInputField.Select();
}// END Start()
 
function Update () {
	TextLabel.text = 'Your name is: ' + TextGetInputField.text;
}// END Update()

Hierarchy> Canvas/InputField> DRAG AND DROP over var MyInputField
Hierarchy> Canvas/InputField/Text> DRAG AND DROP over var TextGetInputField
Hierarchy> Canvas/Text> DRAG AND DROP over var TextLabel

Play and enjoy!

I like group all UI game objects in a single script, getting they from Inspector, in my opinion it is the easy way to manage a lot of text.

Reference: http://docs.unity3d.com/460/Documentation/ScriptReference/UI.InputField.html