Class InputField
Turn a simple label into a interactable input field.
Implements
Inherited Members
Namespace: UnityEngine.UI
Assembly: UnityEngine.UI.dll
Syntax
[AddComponentMenu("UI (Canvas)/Legacy/Input Field", 103)]
public class InputField : Selectable, IMoveHandler, IPointerDownHandler, IPointerUpHandler, IPointerEnterHandler, IPointerExitHandler, ISelectHandler, IDeselectHandler, IUpdateSelectedHandler, IBeginDragHandler, IDragHandler, IEndDragHandler, IPointerClickHandler, ISubmitHandler, IEventSystemHandler, ICanvasElement, ILayoutElement
Constructors
InputField()
Protected default constructor. Use UnityEngine.GameObject.AddComponent<T>() to add an InputField to a GameObject.
Declaration
protected InputField()
Fields
m_CaretPosition
The character index where the caret is.
Declaration
protected int m_CaretPosition
Field Value
| Type | Description |
|---|---|
| int |
m_CaretSelectPosition
The character index of the selection anchor opposite the caret.
Declaration
protected int m_CaretSelectPosition
Field Value
| Type | Description |
|---|---|
| int |
m_CaretVisible
Whether the blinking caret is currently in its visible phase.
Declaration
protected bool m_CaretVisible
Field Value
| Type | Description |
|---|---|
| bool |
m_CursorVerts
Cached vertex array used to render the caret and selection highlight quads.
Declaration
protected UIVertex[] m_CursorVerts
Field Value
| Type | Description |
|---|---|
| UIVertex[] |
m_DrawEnd
Index one past the last visible character in the scrolled input window.
Declaration
protected int m_DrawEnd
Field Value
| Type | Description |
|---|---|
| int |
m_DrawStart
Index of the first character visible in the scrolled input window.
Declaration
protected int m_DrawStart
Field Value
| Type | Description |
|---|---|
| int |
m_Keyboard
Reference to the on-screen keyboard opened on mobile platforms.
Declaration
protected TouchScreenKeyboard m_Keyboard
Field Value
| Type | Description |
|---|---|
| TouchScreenKeyboard |
m_Mesh
Mesh used to render the caret and selection geometry.
Declaration
[NonSerialized]
protected Mesh m_Mesh
Field Value
| Type | Description |
|---|---|
| Mesh |
m_Placeholder
Serialized backing field for the placeholder graphic shown when the field is empty.
Declaration
[SerializeField]
protected Graphic m_Placeholder
Field Value
| Type | Description |
|---|---|
| Graphic |
m_Text
Serialized backing field for text.
Declaration
[SerializeField]
[Multiline]
[FormerlySerializedAs("mValue")]
protected string m_Text
Field Value
| Type | Description |
|---|---|
| string |
m_TextComponent
Text Text used to display the input's value.
Declaration
[SerializeField]
[FormerlySerializedAs("text")]
protected Text m_TextComponent
Field Value
| Type | Description |
|---|---|
| Text |
Properties
asteriskChar
The character used to hide text in password field.
Declaration
public char asteriskChar { get; set; }
Property Value
| Type | Description |
|---|---|
| char |
Remarks
Not shown in the inspector.
Examples
using UnityEngine;
using System.Collections;
using UnityEngine.UI; // Required when Using UI elements.
public class Example : MonoBehaviour
{
public InputField mainInputField;
void Start()
{
// changes the password symbol. 0 = $, 1 = ! 2 = £ and so on.
mainInputField.asteriskChar = "$!£%&*"[0];
}
}
cachedInputTextGenerator
The TextGenerator used to measure and lay out the input text.
Declaration
protected TextGenerator cachedInputTextGenerator { get; }
Property Value
| Type | Description |
|---|---|
| TextGenerator |
caretBlinkRate
The blinking rate of the input caret, defined as the number of times the blink cycle occurs per second.
Declaration
public float caretBlinkRate { get; set; }
Property Value
| Type | Description |
|---|---|
| float |
caretColor
The custom caret color used if customCaretColor is set.
Declaration
public Color caretColor { get; set; }
Property Value
| Type | Description |
|---|---|
| Color |
caretPosition
Get: Returns the focus position as thats the position that moves around even during selection. Set: Set both the anchor and focus position such that a selection doesn't happen
Declaration
public int caretPosition { get; set; }
Property Value
| Type | Description |
|---|---|
| int |
caretPositionInternal
Current position of the cursor. Getters are public Setters are protected
Declaration
protected int caretPositionInternal { get; set; }
Property Value
| Type | Description |
|---|---|
| int |
caretSelectPositionInternal
Internal accessor for the selection anchor position, clamped to the valid range.
Declaration
protected int caretSelectPositionInternal { get; set; }
Property Value
| Type | Description |
|---|---|
| int |
caretWidth
The width of the caret in pixels.
Declaration
public int caretWidth { get; set; }
Property Value
| Type | Description |
|---|---|
| int |
characterLimit
How many characters the input field is limited to. 0 = infinite.
Declaration
public int characterLimit { get; set; }
Property Value
| Type | Description |
|---|---|
| int |
Examples
using UnityEngine;
using System.Collections;
using UnityEngine.UI; // Required when Using UI elements.
public class Example : MonoBehaviour
{
public InputField mainInputField;
public string playerName;
void Start()
{
//Changes the character limit in the main input field.
mainInputField.characterLimit = playerName.Length;
}
}
characterValidation
The type of validation to perform on a character
Declaration
public InputField.CharacterValidation characterValidation { get; set; }
Property Value
| Type | Description |
|---|---|
| InputField.CharacterValidation |
contentType
Specifies the type of the input text content.
Declaration
public InputField.ContentType contentType { get; set; }
Property Value
| Type | Description |
|---|---|
| InputField.ContentType |
Remarks
The ContentType affects character validation, keyboard type used (on platforms with on-screen keyboards), whether the InputField accepts multiple lines, and whether the text is autocorrected (on platforms that offer input auto-correction) or is treated as a password where the characters are not shown directly.
Examples
using UnityEngine;
using System.Collections;
using UnityEngine.UI; // Required when Using UI elements.
public class Example : MonoBehaviour
{
public InputField mainInputField;
public string playerName;
void Start()
{
//Changes the character limit in the main input field.
mainInputField.characterLimit = playerName.Length;
}
}
customCaretColor
Should a custom caret color be used or should the textComponent.color be used.
Declaration
public bool customCaretColor { get; set; }
Property Value
| Type | Description |
|---|---|
| bool |
flexibleHeight
The extra relative height this layout element should be allocated if there is additional available space.
Declaration
public virtual float flexibleHeight { get; }
Property Value
| Type | Description |
|---|---|
| float |
Examples
using UnityEngine;
using System.Collections;
using UnityEngine.UI; // Required when using UI elements.
public class ExampleClass : MonoBehaviour
{
public Transform MyContentPanel;
//Sets the flexible height on on all children in the content panel.
public void Start()
{
//Assign all the children of the content panel to an array.
LayoutElement[] myLayoutElements = MyContentPanel.GetComponentsInChildren<LayoutElement>();
//For each child in the array change its LayoutElement's flexible height to 100.
foreach (LayoutElement element in myLayoutElements)
{
element.flexibleHeight = 100f;
}
}
}
flexibleWidth
The extra relative width this layout element should be allocated if there is additional available space.
Declaration
public virtual float flexibleWidth { get; }
Property Value
| Type | Description |
|---|---|
| float |
Remarks
Setting preferredWidth to -1 removed the preferredWidth.
Examples
using UnityEngine;
using System.Collections;
using UnityEngine.UI; // Required when using UI elements.
public class ExampleClass : MonoBehaviour
{
public Transform MyContentPanel;
//Sets the flexible height on on all children in the content panel.
public void Start()
{
//Assign all the children of the content panel to an array.
LayoutElement[] myLayoutElements = MyContentPanel.GetComponentsInChildren<LayoutElement>();
//For each child in the array change its LayoutElement's flexible width to 200.
foreach (LayoutElement element in myLayoutElements)
{
element.flexibleWidth = 200f;
}
}
}
inputType
The type of input expected. See InputField.InputType.
Declaration
public InputField.InputType inputType { get; set; }
Property Value
| Type | Description |
|---|---|
| InputField.InputType |
isFocused
Whether the InputField has focus and whether it is able to process events.
Declaration
public bool isFocused { get; }
Property Value
| Type | Description |
|---|---|
| bool |
Examples
using UnityEngine;
using System.Collections;
using UnityEngine.UI; // Required when Using UI elements.
public class Example : MonoBehaviour
{
public GameObject mainInputField;
void Update()
{
//If the input field is focused, change its color to green.
if (mainInputField.GetComponent<InputField>().isFocused == true)
{
mainInputField.GetComponent<Image>().color = Color.green;
}
}
}
keyboardType
They type of mobile keyboard that will be used.
Declaration
public TouchScreenKeyboardType keyboardType { get; set; }
Property Value
| Type | Description |
|---|---|
| TouchScreenKeyboardType |
layoutPriority
The layout priority of this component.
Declaration
public virtual int layoutPriority { get; }
Property Value
| Type | Description |
|---|---|
| int |
Remarks
If multiple components on the same GameObject implement the ILayoutElement interface, the values provided by components that return a higher priority value are given priority. However, values less than zero are ignored. This way a component can override only select properties by leaving the remaning values to be -1 or other values less than zero.
lineType
The LineType used by the InputField.
Declaration
public InputField.LineType lineType { get; set; }
Property Value
| Type | Description |
|---|---|
| InputField.LineType |
Examples
using UnityEngine;
using System.Collections;
using UnityEngine.UI; // Required when Using UI elements.
public class Example : MonoBehaviour
{
public GameObject mainInputField;
//When you press a button, this method is called.
public void ChangeInputField(int type)
{
if (type == 0)
{
//Change the input field to "Single Line" line type.
mainInputField.GetComponent<InputField>().lineType = InputField.LineType.SingleLine;
}
else if (type == 1)
{
//Change the input field to "MultiLine Newline" line type.
mainInputField.GetComponent<InputField>().lineType = InputField.LineType.MultiLineNewline;
}
else if (type == 2)
{
//Change the input field to "MultiLine Submit" line type.
mainInputField.GetComponent<InputField>().lineType = InputField.LineType.MultiLineSubmit;
}
}
}
maxHeight
The maximum height this layout element may be allocated.
Declaration
public virtual float maxHeight { get; }
Property Value
| Type | Description |
|---|---|
| float |
maxWidth
The maximum width this layout element may be allocated.
Declaration
public virtual float maxWidth { get; }
Property Value
| Type | Description |
|---|---|
| float |
mesh
The mesh used to render the caret and selection geometry. Created on demand.
Declaration
protected Mesh mesh { get; }
Property Value
| Type | Description |
|---|---|
| Mesh |
minHeight
The minimum height this layout element may be allocated.
Declaration
public virtual float minHeight { get; }
Property Value
| Type | Description |
|---|---|
| float |
minWidth
The minimum width this layout element may be allocated.
Declaration
public virtual float minWidth { get; }
Property Value
| Type | Description |
|---|---|
| float |
multiLine
If the input field supports multiple lines.
Declaration
public bool multiLine { get; }
Property Value
| Type | Description |
|---|---|
| bool |
Examples
using UnityEngine;
using System.Collections;
using UnityEngine.UI; // Required when Using UI elements.
public class Example : MonoBehaviour
{
public InputField mainInputField;
public void Update()
{
//Check to see if the input field is set to allow multiple lines.
if (mainInputField.multiLine)
{
//Set the input field to only allow Single Lines, if it is currently set to allow Multiple lines.
mainInputField.lineType = InputField.LineType.SingleLine;
//Print to console
Debug.Log("The main input field is now set to allow single lines only!");
}
}
}
onEndEdit
The Unity Event to call when editing has ended
Declaration
public InputField.EndEditEvent onEndEdit { get; set; }
Property Value
| Type | Description |
|---|---|
| InputField.EndEditEvent |
Examples
using UnityEngine;
using System.Collections;
using UnityEngine.UI; // Required when Using UI elements.
public class Example : MonoBehaviour
{
public InputField mainInputField;
// Checks if there is anything entered into the input field.
void LockInput(InputField input)
{
if (input.text.Length > 0)
{
Debug.Log("Text has been entered");
}
else if (input.text.Length == 0)
{
Debug.Log("Main Input Empty");
}
}
public void Start()
{
//Adds a listener that invokes the "LockInput" method when the player finishes editing the main input field.
//Passes the main input field into the method when "LockInput" is invoked
mainInputField.onEndEdit.AddListener(delegate {LockInput(mainInputField); });
}
}
onSubmit
The Unity Event to call when editing has ended
Declaration
public InputField.SubmitEvent onSubmit { get; set; }
Property Value
| Type | Description |
|---|---|
| InputField.SubmitEvent |
Examples
using UnityEngine;
using System.Collections;
using UnityEngine.UI; // Required when Using UI elements.
public class Example : MonoBehaviour
{
public InputField mainInputField;
// Checks if there is anything entered into the input field.
void LockInput(InputField input)
{
if (input.text.Length > 0)
{
Debug.Log("Text has been entered");
}
else if (input.text.Length == 0)
{
Debug.Log("Main Input Empty");
}
}
public void Start()
{
//Adds a listener that invokes the "LockInput" method when the player finishes editing the main input field.
//Passes the main input field into the method when "LockInput" is invoked
mainInputField.onSubmit.AddListener(delegate {LockInput(mainInputField); });
}
}
onValidateInput
The function to call to validate the input characters.
Declaration
public InputField.OnValidateInput onValidateInput { get; set; }
Property Value
| Type | Description |
|---|---|
| InputField.OnValidateInput |
Examples
using UnityEngine;
using System.Collections;
using UnityEngine.UI; // Required when Using UI elements.
public class Example : MonoBehaviour
{
public InputField mainInputField;
public void Start()
{
// Sets the MyValidate method to invoke after the input field's default input validation invoke (default validation happens every time a character is entered into the text field.)
mainInputField.onValidateInput += delegate(string input, int charIndex, char addedChar) { return MyValidate(addedChar); };
}
private char MyValidate(char charToValidate)
{
//Checks if a dollar sign is entered....
if (charToValidate == '$')
{
// ... if it is change it to an empty character.
charToValidate = '\0';
}
return charToValidate;
}
}
onValueChanged
Accessor to the OnChangeEvent.
Declaration
public InputField.OnChangeEvent onValueChanged { get; set; }
Property Value
| Type | Description |
|---|---|
| InputField.OnChangeEvent |
Examples
using UnityEngine;
using System.Collections;
using UnityEngine.UI; // Required when Using UI elements.
public class Example : MonoBehaviour
{
public InputField mainInputField;
public void Start()
{
//Adds a listener to the main input field and invokes a method when the value changes.
mainInputField.onValueChanged.AddListener(delegate {ValueChangeCheck(); });
}
// Invoked when the value of the text field changes.
public void ValueChangeCheck()
{
Debug.Log("Value Changed");
}
}
placeholder
This is an optional ‘empty’ graphic to show that the InputField text field is empty. Note that this ‘empty' graphic still displays even when the InputField is selected (that is; when there is focus on it). A placeholder graphic can be used to show subtle hints or make it more obvious that the control is an InputField.
Declaration
public Graphic placeholder { get; set; }
Property Value
| Type | Description |
|---|---|
| Graphic |
Remarks
If a Text component is used as the placeholder, it's recommended to make the placeholder text look different from the real text of the InputField so they are not easily confused. For example, the placeholder text might be a more subtle color or have lower alpha value.
preferredHeight
Get the height of all the text if constrained to the height of the RectTransform.
Declaration
public virtual float preferredHeight { get; }
Property Value
| Type | Description |
|---|---|
| float |
preferredWidth
Get the displayed with of all input characters.
Declaration
public virtual float preferredWidth { get; }
Property Value
| Type | Description |
|---|---|
| float |
readOnly
Set the InputField to be read only.
Declaration
public bool readOnly { get; set; }
Property Value
| Type | Description |
|---|---|
| bool |
Remarks
Setting read only allows for highlighting of text without allowing modifications via keyboard.
selectionAnchorPosition
The beginning point of the selection.
Declaration
public int selectionAnchorPosition { get; set; }
Property Value
| Type | Description |
|---|---|
| int |
Remarks
When making a selection with a mouse, the anchor is where in the document the mouse button is initially pressed. Get: Returns the beginning position of selection Set: If Input.compositionString is 0 set the fixed position.
selectionColor
The color of the highlight to show which characters are selected.
Declaration
public Color selectionColor { get; set; }
Property Value
| Type | Description |
|---|---|
| Color |
Examples
using UnityEngine;
using System.Collections;
using UnityEngine.UI; // Required when Using UI elements.
public class Example : MonoBehaviour
{
public InputField mainInputField;
// Changes the color of the highlight that shows what characters are selected.
void ChangeSelectionColor()
{
mainInputField.selectionColor = Color.red;
}
}
selectionFocusPosition
The end point of the selection.
Declaration
public int selectionFocusPosition { get; set; }
Property Value
| Type | Description |
|---|---|
| int |
Remarks
When making a selection with a mouse, the focus is where in the document the mouse button is released. Get: Returns the end position of selection Set: If Input.compositionString is 0 set the variable position.
shouldActivateOnSelect
Should the inputfield be automatically activated upon selection.
Declaration
public virtual bool shouldActivateOnSelect { get; set; }
Property Value
| Type | Description |
|---|---|
| bool |
shouldHideMobileInput
Should the mobile keyboard input be hidden. This allows for input to happen with a caret in the InputField instead of a OS input box above the keyboard.
Declaration
public bool shouldHideMobileInput { get; set; }
Property Value
| Type | Description |
|---|---|
| bool |
Examples
using UnityEngine;
using System.Collections;
using UnityEngine.UI; // Required when Using UI elements.
public class Example : MonoBehaviour
{
public InputField mainInputField;
public void Start()
{
//This setting can be toggled in the inspector.
mainInputField.shouldHideMobileInput = true;
}
}
text
Input field's current text value. This is not necessarily the same as what is visible on screen.
Declaration
public string text { get; set; }
Property Value
| Type | Description |
|---|---|
| string |
Remarks
Note that null is invalid value for InputField.text.
Examples
using UnityEngine;
using System.Collections;
using UnityEngine.UI; // Required when Using UI elements.
public class Example : MonoBehaviour
{
public InputField mainInputField;
public void Start()
{
mainInputField.text = "Enter Text Here...";
}
}
textComponent
The Text component that is going to be used to render the text to screen.
Declaration
public Text textComponent { get; set; }
Property Value
| Type | Description |
|---|---|
| Text |
touchScreenKeyboard
The TouchScreenKeyboard being used to edit the Input Field.
Declaration
public TouchScreenKeyboard touchScreenKeyboard { get; }
Property Value
| Type | Description |
|---|---|
| TouchScreenKeyboard |
wasCanceled
If the InputField was canceled and will revert back to the original text upon DeactivateInputField.
Declaration
public bool wasCanceled { get; }
Property Value
| Type | Description |
|---|---|
| bool |
Methods
ActivateInputField()
Function to activate the InputField to begin processing Events.
Declaration
public void ActivateInputField()
Remarks
Will only activate if deactivated.
Examples
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class Example : MonoBehaviour
{
public InputField mainInputField;
// Activate the main input field when the scene starts.
void Start()
{
mainInputField.ActivateInputField();
}
}
Append(char)
Append a character to the input field, taking into account the validation of each character.
Declaration
protected virtual void Append(char input)
Parameters
| Type | Name | Description |
|---|---|---|
| char | input | Character to append. |
Append(string)
Append the specified text to the end of the current text string. Appends character by character testing validation criteria.
Declaration
protected virtual void Append(string input)
Parameters
| Type | Name | Description |
|---|---|---|
| string | input | The String to append. |
CalculateLayoutInputHorizontal()
After this method is invoked, layout horizontal input properties should return up-to-date values. Children will already have up-to-date layout horizontal inputs when this method is called.
Declaration
public virtual void CalculateLayoutInputHorizontal()
CalculateLayoutInputVertical()
After this method is invoked, layout vertical input properties should return up-to-date values. Children will already have up-to-date layout vertical inputs when this methods is called.
Declaration
public virtual void CalculateLayoutInputVertical()
ClampPos(ref int)
Clamp a value (by reference) between 0 and the current text length.
Declaration
protected void ClampPos(ref int pos)
Parameters
| Type | Name | Description |
|---|---|---|
| int | pos | The input position to be clampped |
DeactivateInputField()
Function to deactivate the InputField to stop the processing of Events and send OnSubmit if not canceled.
Declaration
public void DeactivateInputField()
Examples
using UnityEngine;
using System.Collections;
using UnityEngine.UI; // Required when Using UI elements.
public class Example : MonoBehaviour
{
public InputField mainInputField;
// Deactivates the main input field when the scene starts.
void Start()
{
mainInputField.DeactivateInputField();
}
}
DoStateTransition(SelectionState, bool)
Applies a visual state transition to the provided state.
Declaration
protected override void DoStateTransition(Selectable.SelectionState state, bool instant)
Parameters
| Type | Name | Description |
|---|---|---|
| Selectable.SelectionState | state | SelectionState to transition to |
| bool | instant | Should the transition occur instantly, without animation. |
Overrides
Remarks
Locks to SelectionState.Selected once focus has been established.
ForceLabelUpdate()
Force the label to update immediatly. This will recalculate the positioning of the caret and the visible text.
Declaration
public void ForceLabelUpdate()
GetCharacterIndexFromPosition(Vector2)
Given an input position in local space on the Text return the index for the selection cursor at this position.
Declaration
protected int GetCharacterIndexFromPosition(Vector2 pos)
Parameters
| Type | Name | Description |
|---|---|---|
| Vector2 | pos | Mouse position. |
Returns
| Type | Description |
|---|---|
| int | Character index with in value. |
GraphicUpdateComplete()
See ICanvasElement.GraphicUpdateComplete. Does nothing by default.
Declaration
public virtual void GraphicUpdateComplete()
KeyPressed(Event)
Process the Event and perform the appropriate action for that key.
Declaration
protected InputField.EditState KeyPressed(Event evt)
Parameters
| Type | Name | Description |
|---|---|---|
| Event | evt | The Event that is currently being processed. |
Returns
| Type | Description |
|---|---|
| InputField.EditState | If we should continue processing events or we have hit an end condition. |
LateUpdate()
Update the text based on input.
Declaration
protected virtual void LateUpdate()
LayoutComplete()
See ICanvasElement.LayoutComplete. Does nothing by default.
Declaration
public virtual void LayoutComplete()
MoveTextEnd(bool)
Move the caret index to end of text.
Declaration
public void MoveTextEnd(bool shift)
Parameters
| Type | Name | Description |
|---|---|---|
| bool | shift | Only move the selection position to facilate selection |
MoveTextStart(bool)
Move the caret index to start of text.
Declaration
public void MoveTextStart(bool shift)
Parameters
| Type | Name | Description |
|---|---|---|
| bool | shift | Only move the selection position to facilate selection |
OnBeginDrag(PointerEventData)
Capture the OnBeginDrag callback from the EventSystem and ensure we should listen to the drag events to follow.
Declaration
public virtual void OnBeginDrag(PointerEventData eventData)
Parameters
| Type | Name | Description |
|---|---|---|
| PointerEventData | eventData | The data passed by the EventSystem |
OnDeselect(BaseEventData)
Unset selection and transition to appropriate state.
Declaration
public override void OnDeselect(BaseEventData eventData)
Parameters
| Type | Name | Description |
|---|---|---|
| BaseEventData | eventData | The base event data. |
Overrides
Remarks
Deactivates the input field.
Examples
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using UnityEngine.EventSystems;// Required when using Event data.
public class ExampleClass : MonoBehaviour, IDeselectHandler //This Interface is required to receive OnDeselect callbacks.
{
public void OnDeselect(BaseEventData data)
{
Debug.Log("Deselected");
}
}
OnDestroy()
Called when destroyed. Unregisters from canvas layout rebuilding.
Declaration
protected override void OnDestroy()
Overrides
OnDisable()
Called when it becomes disabled. Deactivates the input field and unregisters callbacks. It also releases the caret and selection mesh.
Declaration
protected override void OnDisable()
Overrides
OnDrag(PointerEventData)
Selects the character range under the bounding rectangle during a drag operation.
Declaration
public virtual void OnDrag(PointerEventData eventData)
Parameters
| Type | Name | Description |
|---|---|---|
| PointerEventData | eventData | The pointer event data for the drag. |
Remarks
The event system calls this method when the user drags over the InputField. It updates the caret and selection range based on the drag position so that the selected text expands or shrinks as the user drags. Requires MayDrag(PointerEventData) to return true.
Examples
Override this method to customize drag selection behavior. Call base.OnDrag first so the caret and selection range update correctly; then add custom logic (e.g. limit selection length or update a custom selection indicator).
public override void OnDrag(PointerEventData eventData)
{
base.OnDrag(eventData);
// Clamp selection to a max length.
if (caretSelectPositionInternal - caretPositionInternal > maxSelectionLength)
caretSelectPositionInternal = caretPositionInternal + maxSelectionLength;
}
OnEnable()
Called when it becomes enabled. Registers for material callbacks and updates the label.
Declaration
protected override void OnEnable()
Overrides
OnEndDrag(PointerEventData)
Capture the OnEndDrag callback from the EventSystem and cancel the listening of drag events.
Declaration
public virtual void OnEndDrag(PointerEventData eventData)
Parameters
| Type | Name | Description |
|---|---|---|
| PointerEventData | eventData | The eventData sent by the EventSystem. |
OnFocus()
Focus the input field initializing properties.
Declaration
protected void OnFocus()
Remarks
Handles what happens after a user selects an InputField. This is a protected property. To return the focus state use InputField.isFocused. To shift focus to another GameObject, use EventSystem.SetSelectedGameObject. A common use of this is allowing the user to type once focussed. Another way is outputting a message when the user clicks on a field(often seen when creating passwords).
Examples
Create an Input Field by going to __Create__>__UI__>__Input Field__. Attach this script to the Input Field GameObject.
using UnityEngine;
using UnityEngine.UI;
public class Example : MonoBehaviour
{
InputField m_InputField;
void Start()
{
//Fetch the Input Field component from the GameObject
m_InputField = GetComponent<InputField>();
}
void Update()
{
//Check if the Input Field is in focus and able to alter
if (m_InputField.isFocused)
{
//Change the Color of the Input Field's Image to green
m_InputField.GetComponent<Image>().color = Color.green;
}
}
}
OnPointerClick(PointerEventData)
Use this callback to detect clicks.
Declaration
public virtual void OnPointerClick(PointerEventData eventData)
Parameters
| Type | Name | Description |
|---|---|---|
| PointerEventData | eventData | The pointer event data for the click. |
OnPointerDown(PointerEventData)
Called when the pointer is pressed. Evaluates the current selection state and transitions to the appropriate state.
Declaration
public override void OnPointerDown(PointerEventData eventData)
Parameters
| Type | Name | Description |
|---|---|---|
| PointerEventData | eventData | The pointer event data for the press. |
Overrides
Remarks
Handles focus for the input field and positions the text caret.
Examples
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using UnityEngine.EventSystems;// Required when using Event data.
public class ExampleClass : MonoBehaviour, IPointerDownHandler// required interface when using the OnPointerDown method.
{
//Do this when the mouse is clicked over the selectable object this script is attached to.
public void OnPointerDown(PointerEventData eventData)
{
Debug.Log(this.gameObject.name + " Was Clicked.");
}
}
OnSelect(BaseEventData)
Set selection and transition to appropriate state.
Declaration
public override void OnSelect(BaseEventData eventData)
Parameters
| Type | Name | Description |
|---|---|---|
| BaseEventData | eventData | The base event data. |
Overrides
Examples
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using UnityEngine.EventSystems;// Required when using Event data.
public class ExampleClass : MonoBehaviour, ISelectHandler// required interface when using the OnSelect method.
{
//Do this when the selectable UI object is selected.
public void OnSelect(BaseEventData eventData)
{
Debug.Log(this.gameObject.name + " was selected");
}
}
OnSubmit(BaseEventData)
Called when a submit event occurs.
Declaration
public virtual void OnSubmit(BaseEventData eventData)
Parameters
| Type | Name | Description |
|---|---|---|
| BaseEventData | eventData | The base event data. |
Remarks
Finishes editing if the field is focused.
OnUpdateSelected(BaseEventData)
What to do when the event system sends a Update selected Event.
Declaration
public virtual void OnUpdateSelected(BaseEventData eventData)
Parameters
| Type | Name | Description |
|---|---|---|
| BaseEventData | eventData | The data on which to process. |
OnValidate()
Declaration
protected override void OnValidate()
Overrides
ProcessEvent(Event)
Helper function to allow separate events to be processed by the InputField.
Declaration
public void ProcessEvent(Event e)
Parameters
| Type | Name | Description |
|---|---|---|
| Event | e | The Event to process |
Rebuild(CanvasUpdate)
Rebuild the input fields geometry. (caret and highlight).
Declaration
public virtual void Rebuild(CanvasUpdate update)
Parameters
| Type | Name | Description |
|---|---|---|
| CanvasUpdate | update | Which update loop we are in. |
SelectAll()
Highlight the whole InputField.
Declaration
protected void SelectAll()
Remarks
Sets the caretPosition to the length of the text and caretSelectPos to 0.
SendOnEndEdit()
Convenience function to make functionality to send the ::ref::EndEditEvent easier.
Declaration
protected void SendOnEndEdit()
SendOnSubmit()
Convenience function to make functionality to send the ::ref::SubmitEvent easier.
Declaration
protected void SendOnSubmit()
SetTextWithoutNotify(string)
Set the current text value of the Input field without invoking onValueChanged.
Declaration
public void SetTextWithoutNotify(string input)
Parameters
| Type | Name | Description |
|---|---|---|
| string | input | The new text value to set. |
Remarks
This is not necessarily the same as what is visible on screen.
UpdateLabel()
Update the Text associated with this input field.
Declaration
protected void UpdateLabel()
Validate(string, int, char)
Predefined validation functionality for different characterValidation types.
Declaration
protected char Validate(string text, int pos, char ch)
Parameters
| Type | Name | Description |
|---|---|---|
| string | text | The whole text string to validate. |
| int | pos | The position at which the current character is being inserted. |
| char | ch | The character that is being inserted |
Returns
| Type | Description |
|---|---|
| char | The character that should be inserted. |