Search Unity

[Solved] How does InputField.caretPosition work?

Discussion in 'UGUI & TextMesh Pro' started by JasonBricco, Mar 10, 2016.

  1. JasonBricco

    JasonBricco

    Joined:
    Jul 15, 2013
    Posts:
    956
    This is a very simple question, and maybe I'm just doing something stupid. The documentation is very vague. I assumed that caretPosition returns the number of characters into the input string. That does not seem to be the case.

    I have an editor. I have a button in this editor. When you press it, it disables the editor and lets you select a tile. When you do, it opens the editor back up and is supposed to input the coordinates of that tile into the editor.

    What I want to do is save the caret position before disabling the editor. When opening the editor back up (after selecting a tile), it should put the coordinates where the caret was rather than at the end of the string.

    Apparently, caretPosition returns 0 no matter where it is in the string. This leads me to believe I do not understand how it works, and the documentation isn't very helpful. So why is it always returning 0?

    As an aside, I wanted to have the ability to select text in this editor and have any selected text be replaced by the coordinates returned using the above system.

    Unfortunately, I can't seem to figure out how to get the selected text. caretPosition apparently returns the 'selection tail' (end of the selection), and selectionFocusPosition also returns the end.

    So, how do I get the beginning of the selection? I have no idea. Maybe I'm just searching in the wrong place for these things...

    Any help would be appreciated.
     
  2. JasonBricco

    JasonBricco

    Joined:
    Jul 15, 2013
    Posts:
    956
    Alright, I solved it.

    When you press the button, the caret disappears and the position is set to 0 (because the focus isn't in the text anymore). I suppose I thought that it would still save the last position of the caret if focus is lost. That is not so.

    And that makes my life more difficult!
     
  3. digimbyte

    digimbyte

    Joined:
    Jun 23, 2012
    Posts:
    58
    its probably WAY too late, but what you should do is have a tracking variable that gets the caretPosition every frame, and when you press a button, it modifies that variable and then you set focus to that input again and then set its caret Position to that stored variable

    example would be
    private int caretCache;

    if (text focused)
    caretCache = MyText.Input.caretPosition();

    onGui(button){
    caretCache -= 1;
    }

    ofcourse, you have other functions like
    https://docs.unity3d.com/ScriptReference/UI.InputField-selectionAnchorPosition.html

    and
    https://docs.unity3d.com/ScriptReference/UI.InputField.MoveTextStart.html

    Which are more useful for your purpose
     
    Last edited: Nov 24, 2018
    laurentlavigne and JackofTraes like this.