When an InputField is activated, either by clicking on it or by calling its ActivateInputField() function, all of the text in that input field is automatically selected (that is, highlighted, such that anything typed will replace what was already there, unless the mouse is first clicked somewhere in the text to deselect it and position the caret).
I would like to be able to either:
-
Not select the text when the InputField is activated, and just have the caret positioned at the end so that whatever is typed will be added to the end of the text that’s already there; or:
-
Deselect the text and move the caret to the end, via script. I tried the MoveTextEnd() function, with the “shift” parameter set to true or false, and this did not result in the text being deselected.
Any help would be greatly appreciated!
I found a solution to this, with the help of these forum posts:
http://forum.unity3d.com/threads/inputfield-highlighting-movetextend.315091/
http://forum.unity3d.com/threads/how-to-wait-for-a-frame-in-c.24616/
The trick is that due to the way the UI system works, the selected UI element is only updated later in the frame, so moving the caret to the end (and deselecting the text) can only be done at the end of the frame, or in the next frame. Here’s the code I used to move the caret to the end, and deselect the text, during the next frame after the input field is selected:
{
// Activate and select the chatInputField to allow the player to just continue typing.
chatInputField.ActivateInputField();
chatInputField.Select();
// Start a coroutine to deselect text and move caret to end.
// This can't be done now, must be done in the next frame.
StartCoroutine(MoveTextEnd_NextFrame());
}
IEnumerator MoveTextEnd_NextFrame()
{
yield return 0; // Skip the first frame in which this is called.
chatInputField.MoveTextEnd(false); // Do this during the next frame.
}
Note that another possible solution is to create a subclass of InputField, and have that subclass’s LateUpdate() method call MoveToEnd() (after calling base.LateUpdate()). This way it can be done during the same frame in which the InputField is activated, but late enough in the frame that the text will be deselected.