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

What do I want to achieve?
Show a context menu on top of highlighted text area like this.
8308554--1090023--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

  • How to detect when text is highlighted in input fields
  • How to get the highlighted string
  • How to get its position

What solutions have I tried so far?

8308554--1090023--upload_2022-7-25_3-9-50.gif

Hi!

You can add a selection listener to the input field.

    private void Awake()
    {
        inputField.onTextSelection.AddListener(GetSelectedText);
    }
 
    private void GetSelectedText(string str, int start, int end)
    {
         string selectedText = str.Substring(Mathf.Min(start, end), Mathf.Abs(end - start));
         UnityEngine.Debug.Log(selectedText);
    }

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.

Thank you very much. That was invaluably helpful!

Phew, this saved me, too! Is this fact documented anywhere else? Feels like a key detail to mention in the docs for these properties