Search Unity

Working with TextArea and selected text

Discussion in 'Scripting' started by toomas, Jan 15, 2012.

  1. toomas

    toomas

    Joined:
    Jun 19, 2009
    Posts:
    16
    I am trying to build a text editor like functionality in Unity. It seems natural to use GUI.TextArea for this, but I can't seem to find an easy way to work with text selections. What I'd like to do is that when user selects some text and presses a button, then this selected text is taken and copied somewhere. Right now I see two options how I can do it and both involve quite much coding and look ugly.

    1. Use guiStyle.GetCursorStringIndex together with Input class. When mouse goes down mark it as selection start and when mouse goes up, end it. When shift+left is pressed then one character is applied to the selection from left or right, when ctrl+shift+left is pressed, then add one word, when ctrl+a is pressed, then ... and so on. I feel there should be an easier way.

    2. Create text editor from scratch using character drawing function (luckily I have fixed-width font) or somehow use guiStyle.DrawWithTextSelection which seems to be too low level for me and I don'r know how to use it. Again, lots of work.

    Also, I don't know where is the keyboard cursor inside the textarea, so I see as an only choice to track this myself and hope Unity tracks it the same way. Very ugly.

    What are my options? How can I accomplish this?

    If anyone could provide an example of text editor with features the following, I'd be super happy. But any hints or ideas would help too. Thanks in advance!
    - looks like an editable textarea as usual
    - under the textarea there is a button "copy". Pressing it will just Debug.Log it out.
    - optionally copy would push the selected part into system clipboard
     
  2. TheCheese

    TheCheese

    Joined:
    Nov 25, 2009
    Posts:
    82
    I was just dealing with this same problem recently and came by this bit of code on the forums -

    Code (csharp):
    1.  
    2. function OnGUI(){
    3.     // be sure to check if your textfield has keyboard focus first - -
    4.  
    5.     var te : TextEditor = GUIUtility.GetStateObject((TextEditor), GUIUtility.keyboardControl);
    6.     // the TextEditor class is really very nice - you can control selections, move the cursor and a whole lot more
    7.  
    8.     if (te != null){
    9.         print(te.SelectedText);
    10.     }
    11. }
    12.  
    It's really very annoying that there is ZERO documentation about the TextEditor class. You basically have to rely on MonoDevelop's autocomplete or play with reflection to see what your options are.

    That said - it is a really good class and will allow you to do pretty much anything you can think of that you'd want to do in a TextField.