Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

Question How to get highlighted text and the highlighted word position from InputField?

Discussion in 'UGUI & TextMesh Pro' started by TEDDGames, Jul 25, 2022.

  1. TEDDGames

    TEDDGames

    Joined:
    Mar 9, 2020
    Posts:
    2
    What do I want to achieve?
    Show a context menu on top of highlighted text area like this.
    upload_2022-7-25_3-9-50.gif

    What is my issue?
    I don't know how to get any info about selected text. I want to know
    1. How to detect when text is highlighted in input fields
    2. How to get the highlighted string
    3. How to get its position
    What solutions have I tried so far?
    1. I've read Unity docs about InputFields to see if there is any method or property that returns highlighted text or it's position. The closest thing that intuitively made sense was InputField.selectionFocusPosition but it returns an int (I assume it's an index or something). Personally I'd find it intuitive to get a vector.
    2. I read old post this post: Is it possible to retrieve InputField selected text from (2015) but it didn't quite answer my question.
     

    Attached Files:

  2. lluisvinentdev

    lluisvinentdev

    Joined:
    Jun 13, 2022
    Posts:
    3
    Hi!

    You can add a selection listener to the input field.

    Code (CSharp):
    1.  
    2.     private void Awake()
    3.     {
    4.         inputField.onTextSelection.AddListener(GetSelectedText);
    5.     }
    6.  
    7.     private void GetSelectedText(string str, int start, int end)
    8.     {
    9.          string selectedText = str.Substring(Mathf.Min(start, end), Mathf.Abs(end - start));
    10.          UnityEngine.Debug.Log(selectedText);
    11.     }
    Or you can directly use the 'selectionAnchorPosition' and 'selectionFocusPosition' to know the selection positions and get the substring.

    The 'selectionAnchorPosition' is the index where the selection starts.
    And the 'selectionFocusPosition' is the index where the selection ends.

    Beware, their order depends on whether the selection is from left to right or the reverse. That's why I use the Mathf.Min and Mathf.Abs methods, because I don't know which is start or the end.
     
    Last edited: Jul 25, 2022
    TEDDGames likes this.
  3. TEDDGames

    TEDDGames

    Joined:
    Mar 9, 2020
    Posts:
    2
    Thank you very much. That was invaluably helpful!
     
  4. bcjordan

    bcjordan

    Joined:
    Sep 23, 2013
    Posts:
    34
    Phew, this saved me, too! Is this fact documented anywhere else? Feels like a key detail to mention in the docs for these properties